@hakistack/i18n 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 +302 -2
- package/cli/bin.cjs +1411 -0
- package/fesm2022/hakistack-i18n-engine.mjs +394 -0
- package/fesm2022/hakistack-i18n-engine.mjs.map +1 -0
- package/fesm2022/hakistack-i18n.mjs +685 -0
- package/fesm2022/hakistack-i18n.mjs.map +1 -0
- package/package.json +68 -4
- package/schematics/collection.json +15 -0
- package/schematics/ng-add/index.cjs +276 -0
- package/schematics/ng-add/index.cjs.map +1 -0
- package/schematics/ng-add/schema.js +3 -0
- package/schematics/ng-add/schema.js.map +1 -0
- package/schematics/ng-add/schema.json +37 -0
- package/types/hakistack-i18n-engine.d.ts +324 -0
- package/types/hakistack-i18n.d.ts +508 -0
package/cli/bin.cjs
ADDED
|
@@ -0,0 +1,1411 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
18
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
19
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
20
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
21
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
|
+
mod
|
|
24
|
+
));
|
|
25
|
+
|
|
26
|
+
// projects/hakistack/i18n/cli/bin.ts
|
|
27
|
+
var path9 = __toESM(require("path"));
|
|
28
|
+
|
|
29
|
+
// projects/hakistack/i18n/cli/generate.ts
|
|
30
|
+
var path4 = __toESM(require("path"));
|
|
31
|
+
|
|
32
|
+
// projects/hakistack/i18n/engine/merge.ts
|
|
33
|
+
function isTree(value) {
|
|
34
|
+
return typeof value === "object" && value !== null;
|
|
35
|
+
}
|
|
36
|
+
function cloneTree(tree) {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const [key, value] of Object.entries(tree)) out[key] = isTree(value) ? cloneTree(value) : value;
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
function mergeInto(target, source, path10 = "", keysTree = false) {
|
|
42
|
+
for (const [key, value] of Object.entries(source)) {
|
|
43
|
+
const at = path10 ? `${path10}.${key}` : key;
|
|
44
|
+
const existing = target[key];
|
|
45
|
+
if (existing === void 0) {
|
|
46
|
+
target[key] = isTree(value) ? cloneTree(value) : value;
|
|
47
|
+
} else if (isTree(existing) && isTree(value)) {
|
|
48
|
+
mergeInto(existing, value, at, keysTree);
|
|
49
|
+
} else if (!isTree(existing) && !isTree(value)) {
|
|
50
|
+
throw new Error(`i18n: duplicate translation key '${keysTree ? String(existing) : at}' \u2014 it is defined by more than one module.`);
|
|
51
|
+
} else {
|
|
52
|
+
throw new Error(`i18n: '${at}' is both a translation and a group of translations (check modules sharing or nesting this scope).`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function nestAtScope(scope, subtree) {
|
|
57
|
+
return scope.split(".").reverse().reduce((inner, part) => ({ [part]: inner }), subtree);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// projects/hakistack/i18n/engine/define-translations.ts
|
|
61
|
+
var SOURCE_LANG = "en";
|
|
62
|
+
var TRANSLATION_BRAND = /* @__PURE__ */ Symbol.for("@hakistack/i18n:translation-value");
|
|
63
|
+
function isTranslationValue(value) {
|
|
64
|
+
return value !== null && typeof value === "object" && value[TRANSLATION_BRAND] === true;
|
|
65
|
+
}
|
|
66
|
+
function findKeyConflicts(modules) {
|
|
67
|
+
const leaves = [];
|
|
68
|
+
const walk = (node, prefix, scope) => {
|
|
69
|
+
for (const [key, value] of Object.entries(node)) {
|
|
70
|
+
const full = `${prefix}.${key}`;
|
|
71
|
+
if (isTranslationValue(value)) leaves.push({ key: full, scope });
|
|
72
|
+
else if (typeof value === "object" && value !== null) walk(value, full, scope);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
for (const mod of modules) walk(mod.translations, mod.scope, mod.scope);
|
|
76
|
+
return conflictsFromLeaves(leaves);
|
|
77
|
+
}
|
|
78
|
+
function conflictsFromLeaves(leaves) {
|
|
79
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
80
|
+
const groups = /* @__PURE__ */ new Map();
|
|
81
|
+
const add = (map, key, scope) => map.set(key, [...map.get(key) ?? [], scope]);
|
|
82
|
+
for (const { key, scope } of leaves) {
|
|
83
|
+
add(byKey, key, scope);
|
|
84
|
+
const parts = key.split(".");
|
|
85
|
+
for (let i = 1; i < parts.length; i++) add(groups, parts.slice(0, i).join("."), scope);
|
|
86
|
+
}
|
|
87
|
+
const conflicts = [];
|
|
88
|
+
for (const [key, scopes] of byKey) {
|
|
89
|
+
if (scopes.length > 1) conflicts.push({ key, kind: "duplicate", scopes });
|
|
90
|
+
const groupScopes = groups.get(key);
|
|
91
|
+
if (groupScopes) conflicts.push({ key, kind: "translation-and-group", scopes: [.../* @__PURE__ */ new Set([...scopes, ...groupScopes])] });
|
|
92
|
+
}
|
|
93
|
+
return conflicts.sort((a, b) => a.key.localeCompare(b.key));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// projects/hakistack/i18n/engine/build-tree.ts
|
|
97
|
+
function getTranslation(value, lang, defaultLang) {
|
|
98
|
+
const byLang = value;
|
|
99
|
+
if (lang === defaultLang) {
|
|
100
|
+
return byLang[defaultLang] ?? value.en;
|
|
101
|
+
}
|
|
102
|
+
return byLang[lang] ?? byLang[defaultLang] ?? value.en;
|
|
103
|
+
}
|
|
104
|
+
function extractLanguage(translations, lang, defaultLang, options = {}) {
|
|
105
|
+
const comments = options.comments ?? true;
|
|
106
|
+
const result = {};
|
|
107
|
+
for (const [key, value] of Object.entries(translations)) {
|
|
108
|
+
if (isTranslationValue(value)) {
|
|
109
|
+
result[key] = getTranslation(value, lang, defaultLang);
|
|
110
|
+
if (comments && value.__comment) {
|
|
111
|
+
result[`${key}.comment`] = value.__comment;
|
|
112
|
+
}
|
|
113
|
+
} else if (typeof value === "object" && value !== null) {
|
|
114
|
+
result[key] = extractLanguage(value, lang, defaultLang, options);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
119
|
+
function setAtScope(target, scope, subtree) {
|
|
120
|
+
mergeInto(target, nestAtScope(scope, subtree));
|
|
121
|
+
}
|
|
122
|
+
function buildLanguageTree(registry, lang, defaultLang, options) {
|
|
123
|
+
const tree = {};
|
|
124
|
+
for (const mod of registry) {
|
|
125
|
+
setAtScope(tree, mod.scope, extractLanguage(mod.translations, lang, defaultLang, options));
|
|
126
|
+
}
|
|
127
|
+
return tree;
|
|
128
|
+
}
|
|
129
|
+
function buildScopedTree(registry, lang, defaultLang, scope, options) {
|
|
130
|
+
const wanted = normalizeScope(scope);
|
|
131
|
+
const modules = registry.filter((mod) => mod.scoped && normalizeScope(mod.scope) === wanted);
|
|
132
|
+
if (modules.length === 0) return null;
|
|
133
|
+
const tree = {};
|
|
134
|
+
for (const mod of modules) mergeInto(tree, extractLanguage(mod.translations, lang, defaultLang, options), wanted);
|
|
135
|
+
return tree;
|
|
136
|
+
}
|
|
137
|
+
function scopeToFilesystemPath(scope) {
|
|
138
|
+
return scope.replace(/\./g, "/");
|
|
139
|
+
}
|
|
140
|
+
function normalizeScope(scope) {
|
|
141
|
+
return scope.replace(/\//g, ".");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// projects/hakistack/i18n/cli/load-registry.ts
|
|
145
|
+
var fs = __toESM(require("fs"));
|
|
146
|
+
var path = __toESM(require("path"));
|
|
147
|
+
var import_jiti = require("jiti");
|
|
148
|
+
function barrelPath(config) {
|
|
149
|
+
return path.join(config.definitionsDir, "index.generated.ts");
|
|
150
|
+
}
|
|
151
|
+
function keysPath(config) {
|
|
152
|
+
return path.join(config.definitionsDir, "keys.generated.ts");
|
|
153
|
+
}
|
|
154
|
+
var importFresh = (file) => (0, import_jiti.createJiti)(__filename, { moduleCache: false }).import(file);
|
|
155
|
+
function ensureExists(file, hint) {
|
|
156
|
+
if (!fs.existsSync(file)) {
|
|
157
|
+
throw new Error(`i18n: expected generated file not found:
|
|
158
|
+
${file}
|
|
159
|
+
${hint}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async function loadRegistry(config) {
|
|
163
|
+
const file = barrelPath(config);
|
|
164
|
+
ensureExists(file, "Run the `scan` command first (`hakistack-i18n scan`).");
|
|
165
|
+
const mod = await importFresh(file);
|
|
166
|
+
if (!mod.ALL_TRANSLATIONS) {
|
|
167
|
+
throw new Error(`i18n: '${file}' does not export ALL_TRANSLATIONS. Re-run the scan.`);
|
|
168
|
+
}
|
|
169
|
+
return mod.ALL_TRANSLATIONS;
|
|
170
|
+
}
|
|
171
|
+
async function loadKeys(config) {
|
|
172
|
+
const file = keysPath(config);
|
|
173
|
+
ensureExists(file, "Run the `scan` command first (`hakistack-i18n scan`).");
|
|
174
|
+
const mod = await importFresh(file);
|
|
175
|
+
if (!mod.TK) {
|
|
176
|
+
throw new Error(`i18n: '${file}' does not export TK. Re-run the scan.`);
|
|
177
|
+
}
|
|
178
|
+
return mod.TK;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// projects/hakistack/i18n/cli/output.ts
|
|
182
|
+
var fs2 = __toESM(require("fs"));
|
|
183
|
+
var path2 = __toESM(require("path"));
|
|
184
|
+
function writeFileAtomic(file, content) {
|
|
185
|
+
fs2.mkdirSync(path2.dirname(file), { recursive: true });
|
|
186
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
187
|
+
fs2.writeFileSync(tmp, content, "utf-8");
|
|
188
|
+
fs2.renameSync(tmp, file);
|
|
189
|
+
}
|
|
190
|
+
function writeIfChanged(file, content) {
|
|
191
|
+
if (fs2.existsSync(file) && fs2.readFileSync(file, "utf-8") === content) return false;
|
|
192
|
+
writeFileAtomic(file, content);
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
function manifestPath(cwd) {
|
|
196
|
+
for (let dir = cwd; ; dir = path2.dirname(dir)) {
|
|
197
|
+
if (fs2.existsSync(path2.join(dir, "node_modules"))) return path2.join(dir, "node_modules", ".cache", "hakistack-i18n", "manifest.json");
|
|
198
|
+
if (path2.dirname(dir) === dir) return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function readManifest(file) {
|
|
202
|
+
try {
|
|
203
|
+
return JSON.parse(fs2.readFileSync(file, "utf-8"));
|
|
204
|
+
} catch {
|
|
205
|
+
return {};
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function syncOutputs(cwd, producer, root, outputs) {
|
|
209
|
+
const result = { written: [], unchanged: [], removed: [] };
|
|
210
|
+
for (const { file, content } of outputs) (writeIfChanged(file, content) ? result.written : result.unchanged).push(file);
|
|
211
|
+
const mPath = manifestPath(cwd);
|
|
212
|
+
if (!mPath) return result;
|
|
213
|
+
const manifest = readManifest(mPath);
|
|
214
|
+
const current = new Set(outputs.map((o) => path2.resolve(o.file)));
|
|
215
|
+
const inside = (file) => !path2.relative(root, file).startsWith("..") && !path2.isAbsolute(path2.relative(root, file));
|
|
216
|
+
for (const previous of manifest[producer] ?? []) {
|
|
217
|
+
if (current.has(previous) || !inside(previous) || !fs2.existsSync(previous)) continue;
|
|
218
|
+
fs2.rmSync(previous);
|
|
219
|
+
result.removed.push(previous);
|
|
220
|
+
removeEmptyDirs(path2.dirname(previous), root);
|
|
221
|
+
}
|
|
222
|
+
manifest[producer] = [...current].sort();
|
|
223
|
+
writeIfChanged(mPath, JSON.stringify(manifest, null, 2) + "\n");
|
|
224
|
+
return result;
|
|
225
|
+
}
|
|
226
|
+
function removeEmptyDirs(dir, root) {
|
|
227
|
+
for (let d = dir; d !== root && !path2.relative(root, d).startsWith(".."); d = path2.dirname(d)) {
|
|
228
|
+
if (fs2.readdirSync(d).length > 0) return;
|
|
229
|
+
fs2.rmdirSync(d);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// projects/hakistack/i18n/cli/discover.ts
|
|
234
|
+
var fs3 = __toESM(require("fs"));
|
|
235
|
+
var import_module = require("module");
|
|
236
|
+
var path3 = __toESM(require("path"));
|
|
237
|
+
var I18N_SUFFIX = ".i18n.ts";
|
|
238
|
+
var DEFINE = "defineTranslations";
|
|
239
|
+
var LEAF = "t";
|
|
240
|
+
var cachedTs = null;
|
|
241
|
+
function loadTypeScript(cwd) {
|
|
242
|
+
if (cachedTs) return cachedTs;
|
|
243
|
+
for (const from of [path3.join(cwd, "package.json"), __filename]) {
|
|
244
|
+
try {
|
|
245
|
+
cachedTs = (0, import_module.createRequire)(from)("typescript");
|
|
246
|
+
return cachedTs;
|
|
247
|
+
} catch {
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
throw new Error('i18n: the codegen needs the "typescript" package. Install it with:\n npm i -D typescript');
|
|
251
|
+
}
|
|
252
|
+
function collectI18nFiles(dir, out = []) {
|
|
253
|
+
if (!fs3.existsSync(dir)) return out;
|
|
254
|
+
const entries = fs3.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
255
|
+
for (const entry of entries) {
|
|
256
|
+
if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
|
|
257
|
+
const full = path3.join(dir, entry.name);
|
|
258
|
+
if (entry.isDirectory()) collectI18nFiles(full, out);
|
|
259
|
+
else if (entry.isFile() && entry.name.endsWith(I18N_SUFFIX)) out.push(full);
|
|
260
|
+
}
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
function toImportPath(sourceFile, definitionsDir) {
|
|
264
|
+
const posix = path3.relative(definitionsDir, sourceFile).replace(/\.ts$/, "").split(path3.sep).join("/");
|
|
265
|
+
return posix.startsWith(".") ? posix : "./" + posix;
|
|
266
|
+
}
|
|
267
|
+
function discover(config) {
|
|
268
|
+
const ts = loadTypeScript(config.cwd);
|
|
269
|
+
const modules = [];
|
|
270
|
+
const issues = [];
|
|
271
|
+
for (const file of collectI18nFiles(config.srcRoot)) {
|
|
272
|
+
const found = discoverFile(ts, file, fs3.readFileSync(file, "utf-8"), issues);
|
|
273
|
+
const importPath = toImportPath(file, config.definitionsDir);
|
|
274
|
+
for (const mod of found) modules.push({ ...mod, importPath });
|
|
275
|
+
}
|
|
276
|
+
modules.sort((a, b) => a.exportName.localeCompare(b.exportName) || a.sourceFile.localeCompare(b.sourceFile));
|
|
277
|
+
return { modules, issues };
|
|
278
|
+
}
|
|
279
|
+
function discoverFile(ts, file, text, issues) {
|
|
280
|
+
const fileIssues = [];
|
|
281
|
+
const found = scanSourceFile(ts, file, text, fileIssues);
|
|
282
|
+
issues.push(...fileIssues.sort((a, b) => a.line - b.line));
|
|
283
|
+
return found;
|
|
284
|
+
}
|
|
285
|
+
function scanSourceFile(ts, file, text, issues) {
|
|
286
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
287
|
+
const lineOf = (node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
|
|
288
|
+
const issue = (node, severity, message) => issues.push({ file, line: lineOf(node), severity, message });
|
|
289
|
+
const defineNames = /* @__PURE__ */ new Set([DEFINE]);
|
|
290
|
+
const leafNames = /* @__PURE__ */ new Set([LEAF]);
|
|
291
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
292
|
+
for (const stmt of sf.statements) {
|
|
293
|
+
const bindings = ts.isImportDeclaration(stmt) ? stmt.importClause?.namedBindings : void 0;
|
|
294
|
+
if (!bindings) continue;
|
|
295
|
+
if (ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text);
|
|
296
|
+
else
|
|
297
|
+
for (const el of bindings.elements) {
|
|
298
|
+
const imported = (el.propertyName ?? el.name).text;
|
|
299
|
+
if (imported === DEFINE) defineNames.add(el.name.text);
|
|
300
|
+
if (imported === LEAF) leafNames.add(el.name.text);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
const unwrap = (node) => ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node) ? unwrap(node.expression) : node;
|
|
304
|
+
const defineCall = (init) => {
|
|
305
|
+
if (!init) return null;
|
|
306
|
+
const call = unwrap(init);
|
|
307
|
+
if (!ts.isCallExpression(call)) return null;
|
|
308
|
+
const callee = call.expression;
|
|
309
|
+
if (ts.isIdentifier(callee) && defineNames.has(callee.text)) return call;
|
|
310
|
+
if (ts.isPropertyAccessExpression(callee) && callee.name.text === DEFINE && ts.isIdentifier(callee.expression)) {
|
|
311
|
+
return namespaces.has(callee.expression.text) ? call : null;
|
|
312
|
+
}
|
|
313
|
+
return null;
|
|
314
|
+
};
|
|
315
|
+
const declared = /* @__PURE__ */ new Map();
|
|
316
|
+
const reExported = /* @__PURE__ */ new Map();
|
|
317
|
+
for (const stmt of sf.statements) {
|
|
318
|
+
if (ts.isVariableStatement(stmt)) {
|
|
319
|
+
const exported = !!stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
|
|
320
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
321
|
+
const call = defineCall(decl.initializer);
|
|
322
|
+
if (call && ts.isIdentifier(decl.name)) declared.set(decl.name.text, { call, node: decl, exported });
|
|
323
|
+
}
|
|
324
|
+
} else if (ts.isExportDeclaration(stmt) && !stmt.moduleSpecifier && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
|
|
325
|
+
for (const el of stmt.exportClause.elements) {
|
|
326
|
+
const local = (el.propertyName ?? el.name).text;
|
|
327
|
+
reExported.set(local, [...reExported.get(local) ?? [], el.name.text]);
|
|
328
|
+
}
|
|
329
|
+
} else if (ts.isExportAssignment(stmt) && defineCall(stmt.expression)) {
|
|
330
|
+
issue(
|
|
331
|
+
stmt,
|
|
332
|
+
"warning",
|
|
333
|
+
"default-exported translation module is ignored \u2014 use a named export (export const NAME = defineTranslations(\u2026))."
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const found = [];
|
|
338
|
+
for (const [local, { call, node, exported }] of declared) {
|
|
339
|
+
const names = [...exported ? [local] : [], ...reExported.get(local) ?? []];
|
|
340
|
+
if (names.length === 0) continue;
|
|
341
|
+
const scopeArg = call.arguments[0] ? unwrap(call.arguments[0]) : void 0;
|
|
342
|
+
const scope = scopeArg && (ts.isStringLiteral(scopeArg) || ts.isNoSubstitutionTemplateLiteral(scopeArg)) ? scopeArg.text : null;
|
|
343
|
+
if (scope === null) {
|
|
344
|
+
issue(call, "warning", `cannot read the scope of '${local}' statically \u2014 use a string literal: defineTranslations('scope', { \u2026 }).`);
|
|
345
|
+
}
|
|
346
|
+
const keys = [];
|
|
347
|
+
let partial = false;
|
|
348
|
+
const treeArg = call.arguments[1] ? unwrap(call.arguments[1]) : void 0;
|
|
349
|
+
if (treeArg && ts.isObjectLiteralExpression(treeArg) && scope !== null) {
|
|
350
|
+
const isLeafCall = (call2) => ts.isIdentifier(call2.expression) && leafNames.has(call2.expression.text) || ts.isPropertyAccessExpression(call2.expression) && call2.expression.name.text === LEAF && ts.isIdentifier(call2.expression.expression) && namespaces.has(call2.expression.expression.text);
|
|
351
|
+
partial = !collectKeys(ts, treeArg, scope, [], keys, { lineOf, isLeafCall });
|
|
352
|
+
} else {
|
|
353
|
+
partial = true;
|
|
354
|
+
}
|
|
355
|
+
found.push({ exportName: names[0], scope, sourceFile: file, line: lineOf(node), keys, partial });
|
|
356
|
+
}
|
|
357
|
+
return found;
|
|
358
|
+
}
|
|
359
|
+
function collectKeys(ts, obj, scope, parents, out, ctx) {
|
|
360
|
+
let complete = true;
|
|
361
|
+
for (const prop of obj.properties) {
|
|
362
|
+
if (!ts.isPropertyAssignment(prop)) {
|
|
363
|
+
complete = false;
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
const name = propertyName(ts, prop.name);
|
|
367
|
+
if (name === null) {
|
|
368
|
+
complete = false;
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
const path10 = [...parents, name];
|
|
372
|
+
const key = `${scope}.${path10.join(".")}`;
|
|
373
|
+
let value = prop.initializer;
|
|
374
|
+
while (ts.isParenthesizedExpression(value) || ts.isAsExpression(value) || ts.isSatisfiesExpression(value)) value = value.expression;
|
|
375
|
+
if (ts.isObjectLiteralExpression(value)) {
|
|
376
|
+
complete = collectKeys(ts, value, scope, path10, out, ctx) && complete;
|
|
377
|
+
} else if (ts.isCallExpression(value) && ctx.isLeafCall(value)) {
|
|
378
|
+
const source = value.arguments[0];
|
|
379
|
+
const text = source && (ts.isStringLiteral(source) || ts.isNoSubstitutionTemplateLiteral(source)) ? source.text : "";
|
|
380
|
+
out.push({ key, path: path10, line: ctx.lineOf(prop), params: placeholderNames(text) });
|
|
381
|
+
} else if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) {
|
|
382
|
+
out.push({ key, path: path10, line: ctx.lineOf(prop), params: [] });
|
|
383
|
+
} else {
|
|
384
|
+
complete = false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return complete;
|
|
388
|
+
}
|
|
389
|
+
function placeholderNames(text) {
|
|
390
|
+
const names = [...text.matchAll(/\{\{([^}]*)}}/g)].map((m) => m[1].trim().split(".")[0]).filter(Boolean);
|
|
391
|
+
return [...new Set(names)].sort();
|
|
392
|
+
}
|
|
393
|
+
function propertyName(ts, name) {
|
|
394
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) {
|
|
395
|
+
return name.text;
|
|
396
|
+
}
|
|
397
|
+
if (ts.isComputedPropertyName(name) && (ts.isStringLiteral(name.expression) || ts.isNoSubstitutionTemplateLiteral(name.expression))) {
|
|
398
|
+
return name.expression.text;
|
|
399
|
+
}
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
function formatLocation(loc, cwd) {
|
|
403
|
+
return `${path3.relative(cwd, loc.file).split(path3.sep).join("/")}:${loc.line}`;
|
|
404
|
+
}
|
|
405
|
+
function keyLocations(modules) {
|
|
406
|
+
const index = /* @__PURE__ */ new Map();
|
|
407
|
+
for (const mod of modules) {
|
|
408
|
+
for (const { key, line } of mod.keys) index.set(key, [...index.get(key) ?? [], { file: mod.sourceFile, line }]);
|
|
409
|
+
}
|
|
410
|
+
return index;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// projects/hakistack/i18n/cli/report.ts
|
|
414
|
+
function describeConflict(c, locations = []) {
|
|
415
|
+
const scopes = [...new Set(c.scopes)];
|
|
416
|
+
const where = `scope${scopes.length > 1 ? "s" : ""} ${scopes.map((s) => `'${s}'`).join(", ")}`;
|
|
417
|
+
const what = c.kind === "duplicate" ? `${c.key} \u2014 defined ${c.scopes.length} times (${where})` : `${c.key} \u2014 is both a translation and a group of translations (${where})`;
|
|
418
|
+
return locations.length ? `${what}
|
|
419
|
+
at ${locations.join("\n at ")}` : what;
|
|
420
|
+
}
|
|
421
|
+
function createKeyLocator(config) {
|
|
422
|
+
try {
|
|
423
|
+
const index = keyLocations(discover(config).modules);
|
|
424
|
+
return (key) => (index.get(key) ?? []).map((loc) => formatLocation(loc, config.cwd));
|
|
425
|
+
} catch {
|
|
426
|
+
return () => [];
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// projects/hakistack/i18n/cli/generate.ts
|
|
431
|
+
function analyze(translations, lang, defaultLang, prefix = "") {
|
|
432
|
+
let total = 0;
|
|
433
|
+
let translated = 0;
|
|
434
|
+
const missing = [];
|
|
435
|
+
for (const [key, value] of Object.entries(translations)) {
|
|
436
|
+
const currentPath = prefix ? `${prefix}.${key}` : key;
|
|
437
|
+
if (isTranslationValue(value)) {
|
|
438
|
+
total++;
|
|
439
|
+
if (value[lang]) {
|
|
440
|
+
translated++;
|
|
441
|
+
} else if (lang !== defaultLang) {
|
|
442
|
+
missing.push(currentPath);
|
|
443
|
+
}
|
|
444
|
+
} else if (typeof value === "object" && value !== null) {
|
|
445
|
+
const nested = analyze(value, lang, defaultLang, currentPath);
|
|
446
|
+
total += nested.total;
|
|
447
|
+
translated += nested.translated;
|
|
448
|
+
missing.push(...nested.missing);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return { total, translated, missing };
|
|
452
|
+
}
|
|
453
|
+
async function runGenerate(config, opts = {}) {
|
|
454
|
+
const info = opts.quiet ? () => void 0 : (m) => console.log(m);
|
|
455
|
+
info("\n\u{1F310} i18n JSON generation\n" + "=".repeat(50));
|
|
456
|
+
const registry = await loadRegistry(config);
|
|
457
|
+
const conflicts = findKeyConflicts(registry);
|
|
458
|
+
if (conflicts.length) {
|
|
459
|
+
const locate = createKeyLocator(config);
|
|
460
|
+
const lines = conflicts.map((c) => ` ${describeConflict(c, locate(c.key))}`).join("\n");
|
|
461
|
+
console.error(`
|
|
462
|
+
\u274C ${conflicts.length} key conflict(s) \u2014 nothing was written:
|
|
463
|
+
${lines}
|
|
464
|
+
`);
|
|
465
|
+
process.exitCode = 1;
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
let totalKeys = 0;
|
|
469
|
+
const translatedByLang = {};
|
|
470
|
+
const missingByLang = {};
|
|
471
|
+
for (const lang of config.locales) {
|
|
472
|
+
translatedByLang[lang] = 0;
|
|
473
|
+
missingByLang[lang] = [];
|
|
474
|
+
for (const mod of registry) {
|
|
475
|
+
const a = analyze(mod.translations, lang, SOURCE_LANG, mod.scope);
|
|
476
|
+
if (lang === SOURCE_LANG) totalKeys += a.total;
|
|
477
|
+
translatedByLang[lang] += a.translated;
|
|
478
|
+
missingByLang[lang].push(...a.missing);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const scopes = [...new Set(registry.filter((m) => m.scoped).map((m) => m.scope))].sort();
|
|
482
|
+
const outputs = [];
|
|
483
|
+
const json = (tree) => JSON.stringify(tree, null, 2) + "\n";
|
|
484
|
+
for (const lang of config.locales) {
|
|
485
|
+
outputs.push({ file: path4.join(config.outputDir, `${lang}.json`), content: json(buildLanguageTree(registry, lang, SOURCE_LANG)) });
|
|
486
|
+
for (const scope of scopes) {
|
|
487
|
+
outputs.push({
|
|
488
|
+
file: path4.join(config.outputDir, scopeToFilesystemPath(scope), `${lang}.json`),
|
|
489
|
+
content: json(buildScopedTree(registry, lang, SOURCE_LANG, scope))
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
const results = [
|
|
494
|
+
syncOutputs(config.cwd, `json:${config.outputDir}`, config.outputDir, outputs),
|
|
495
|
+
syncOutputs(config.cwd, `translations:${config.definitionsDir}`, config.definitionsDir, translationModules(config, registry, scopes))
|
|
496
|
+
];
|
|
497
|
+
const rel = (f) => path4.relative(config.cwd, f);
|
|
498
|
+
for (const f of results.flatMap((r) => r.written)) console.log(`\u2713 ${rel(f)}`);
|
|
499
|
+
for (const f of results.flatMap((r) => r.removed)) console.log(`\u2717 ${rel(f)} (stale \u2014 removed)`);
|
|
500
|
+
const unchanged = results.reduce((n, r) => n + r.unchanged.length, 0);
|
|
501
|
+
if (unchanged) info(`= ${unchanged} file(s) unchanged`);
|
|
502
|
+
info(`
|
|
503
|
+
\u{1F4CA} Coverage
|
|
504
|
+
Total keys: ${totalKeys}`);
|
|
505
|
+
for (const lang of config.locales) {
|
|
506
|
+
const translated = translatedByLang[lang];
|
|
507
|
+
const pct = totalKeys > 0 ? Math.round(translated / totalKeys * 100) : 100;
|
|
508
|
+
info(`${pct === 100 ? "\u2713" : "\u26A0"} ${lang.toUpperCase()}: ${translated}/${totalKeys} (${pct}%)`);
|
|
509
|
+
const missing = missingByLang[lang];
|
|
510
|
+
if (missing.length && lang !== SOURCE_LANG) {
|
|
511
|
+
info(` Missing ${missing.length}: ${missing.slice(0, 3).join(", ")}${missing.length > 3 ? `, \u2026 +${missing.length - 3}` : ""}`);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
info("\n\u2713 Generation complete.\n");
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
var NO_COMMENTS = { comments: false };
|
|
518
|
+
var HEADER = (file) => `/**
|
|
519
|
+
* AUTO-GENERATED \u2014 do not edit by hand (${file}).
|
|
520
|
+
*
|
|
521
|
+
* Produced by \`hakistack-i18n generate\`.
|
|
522
|
+
*/
|
|
523
|
+
`;
|
|
524
|
+
function translationModules(config, registry, scopes) {
|
|
525
|
+
const dir = path4.join(config.definitionsDir, "translations");
|
|
526
|
+
const files = [];
|
|
527
|
+
const loader = (rel) => `() => import('./translations/${rel}.generated')`;
|
|
528
|
+
const q = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
529
|
+
const root = [];
|
|
530
|
+
const scoped = [];
|
|
531
|
+
for (const lang of config.locales) {
|
|
532
|
+
files.push({
|
|
533
|
+
file: path4.join(dir, `${lang}.generated.ts`),
|
|
534
|
+
content: dataModule(`${lang}.generated.ts`, buildLanguageTree(registry, lang, SOURCE_LANG, NO_COMMENTS))
|
|
535
|
+
});
|
|
536
|
+
root.push(` ${q(lang)}: ${loader(lang)},`);
|
|
537
|
+
}
|
|
538
|
+
for (const scope of scopes) {
|
|
539
|
+
const scopePath = scopeToFilesystemPath(scope);
|
|
540
|
+
scoped.push(` ${q(scopePath)}: {`);
|
|
541
|
+
for (const lang of config.locales) {
|
|
542
|
+
const rel = `${scopePath}/${lang}`;
|
|
543
|
+
files.push({
|
|
544
|
+
file: path4.join(dir, `${rel}.generated.ts`),
|
|
545
|
+
content: dataModule(`${lang}.generated.ts`, buildScopedTree(registry, lang, SOURCE_LANG, scope, NO_COMMENTS))
|
|
546
|
+
});
|
|
547
|
+
scoped.push(` ${q(lang)}: ${loader(rel)},`);
|
|
548
|
+
}
|
|
549
|
+
scoped.push(" },");
|
|
550
|
+
}
|
|
551
|
+
const index = [
|
|
552
|
+
HEADER("translations.generated.ts"),
|
|
553
|
+
`import type { I18nTranslationLoaders } from '${config.packageName}';`,
|
|
554
|
+
"",
|
|
555
|
+
"/**",
|
|
556
|
+
" * Per-language translation loaders. Pass to `provideI18n({ keys: TK, translations: TRANSLATIONS })`",
|
|
557
|
+
" * so each language is its own lazily loaded chunk.",
|
|
558
|
+
" */",
|
|
559
|
+
"export const TRANSLATIONS: I18nTranslationLoaders = {",
|
|
560
|
+
" root: {",
|
|
561
|
+
...root,
|
|
562
|
+
" },",
|
|
563
|
+
...scoped.length ? [" scopes: {", ...scoped, " },"] : [],
|
|
564
|
+
"};",
|
|
565
|
+
""
|
|
566
|
+
].join("\n");
|
|
567
|
+
files.push({ file: path4.join(config.definitionsDir, "translations.generated.ts"), content: index });
|
|
568
|
+
return files;
|
|
569
|
+
}
|
|
570
|
+
function dataModule(file, tree) {
|
|
571
|
+
return `${HEADER(file)}export default ${JSON.stringify(tree, null, 2)};
|
|
572
|
+
`;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// projects/hakistack/i18n/cli/scan.ts
|
|
576
|
+
var path5 = __toESM(require("path"));
|
|
577
|
+
function findDuplicateExportNames(modules) {
|
|
578
|
+
const byName = /* @__PURE__ */ new Map();
|
|
579
|
+
for (const mod of modules) byName.set(mod.exportName, [...byName.get(mod.exportName) ?? [], mod]);
|
|
580
|
+
return [...byName].filter(([, mods]) => mods.length > 1);
|
|
581
|
+
}
|
|
582
|
+
function emitBarrel(modules) {
|
|
583
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
584
|
+
for (const mod of modules) {
|
|
585
|
+
if (!byPath.has(mod.importPath)) byPath.set(mod.importPath, []);
|
|
586
|
+
byPath.get(mod.importPath).push(mod.exportName);
|
|
587
|
+
}
|
|
588
|
+
const importEntries = [...byPath.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
589
|
+
const importLines = importEntries.map(([imp, names]) => `import { ${[...names].sort().join(", ")} } from '${imp}';`);
|
|
590
|
+
const reExportLines = importEntries.map(([imp, names]) => `export { ${[...names].sort().join(", ")} } from '${imp}';`);
|
|
591
|
+
const tupleEntries = modules.map((m) => ` ${m.exportName}`).join(",\n");
|
|
592
|
+
return [
|
|
593
|
+
GENERATED_HEADER("index.generated.ts"),
|
|
594
|
+
LOCALES_REFERENCE,
|
|
595
|
+
"",
|
|
596
|
+
...importLines,
|
|
597
|
+
"",
|
|
598
|
+
...reExportLines,
|
|
599
|
+
"",
|
|
600
|
+
"/**",
|
|
601
|
+
" * Tuple of every translation module discovered by the scanner.",
|
|
602
|
+
" * Consumed by the JSON generator and the validator.",
|
|
603
|
+
" */",
|
|
604
|
+
"export const ALL_TRANSLATIONS = [",
|
|
605
|
+
tupleEntries + (tupleEntries ? "," : ""),
|
|
606
|
+
"] as const;",
|
|
607
|
+
""
|
|
608
|
+
].join("\n");
|
|
609
|
+
}
|
|
610
|
+
function newNode() {
|
|
611
|
+
return { leaf: null, params: [], refs: [], children: /* @__PURE__ */ new Map() };
|
|
612
|
+
}
|
|
613
|
+
function buildTKTree(modules) {
|
|
614
|
+
const root = newNode();
|
|
615
|
+
const refs = [];
|
|
616
|
+
const byScope = /* @__PURE__ */ new Map();
|
|
617
|
+
const descend = (parts) => parts.reduce((node, part) => {
|
|
618
|
+
if (!node.children.has(part)) node.children.set(part, newNode());
|
|
619
|
+
return node.children.get(part);
|
|
620
|
+
}, root);
|
|
621
|
+
for (const mod of modules) {
|
|
622
|
+
if (!mod.scope) continue;
|
|
623
|
+
(byScope.get(mod.scope) ?? byScope.set(mod.scope, []).get(mod.scope)).push(mod.exportName);
|
|
624
|
+
const scopeParts = mod.scope.split(".");
|
|
625
|
+
if (mod.partial) {
|
|
626
|
+
descend(scopeParts).refs.push(mod.exportName);
|
|
627
|
+
refs.push(mod.exportName);
|
|
628
|
+
} else {
|
|
629
|
+
descend(scopeParts);
|
|
630
|
+
for (const key of mod.keys) Object.assign(descend([...scopeParts, ...key.path]), { leaf: key.key, params: key.params });
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
const duplicateScopes = new Map([...byScope].filter(([, names]) => names.length > 1));
|
|
634
|
+
return { tree: root, refs: [...new Set(refs)].sort(), duplicateScopes };
|
|
635
|
+
}
|
|
636
|
+
var IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
|
|
637
|
+
function propertyName2(key) {
|
|
638
|
+
return IDENTIFIER_RE.test(key) ? key : quote(key);
|
|
639
|
+
}
|
|
640
|
+
function quote(value) {
|
|
641
|
+
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
642
|
+
}
|
|
643
|
+
function serializeTKNode(node, indent, usage) {
|
|
644
|
+
if (node.leaf !== null && node.children.size === 0 && node.refs.length === 0) {
|
|
645
|
+
if (node.params.length === 0) return quote(node.leaf);
|
|
646
|
+
usage.keyType = true;
|
|
647
|
+
return `${quote(node.leaf)} as I18nKey<${quote(node.leaf)}, ${node.params.map(quote).join(" | ")}>`;
|
|
648
|
+
}
|
|
649
|
+
const childIndent = indent + " ";
|
|
650
|
+
const childEntries = [...node.children.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
651
|
+
const parts = node.refs.map((ref) => `${ref}.keys`);
|
|
652
|
+
if (childEntries.length || parts.length === 0) {
|
|
653
|
+
const lines = ["{"];
|
|
654
|
+
for (const [key, child] of childEntries) {
|
|
655
|
+
lines.push(`${childIndent}${propertyName2(key)}: ${serializeTKNode(child, childIndent, usage)},`);
|
|
656
|
+
}
|
|
657
|
+
lines.push(`${indent}}`);
|
|
658
|
+
parts.push(childEntries.length ? lines.join("\n") : "{}");
|
|
659
|
+
}
|
|
660
|
+
if (parts.length === 1) return parts[0];
|
|
661
|
+
usage.mergeKeys = true;
|
|
662
|
+
return `mergeKeys(${parts.join(", ")})`;
|
|
663
|
+
}
|
|
664
|
+
function emitKeys(modules, packageName) {
|
|
665
|
+
const { tree, refs } = buildTKTree(modules);
|
|
666
|
+
const importLine = refs.length ? `import { ${refs.join(", ")} } from './index.generated';` : "";
|
|
667
|
+
const usage = { mergeKeys: false, keyType: false };
|
|
668
|
+
const topEntries = [...tree.children.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
669
|
+
const body = topEntries.map(([key, child]) => ` ${propertyName2(key)}: ${serializeTKNode(child, " ", usage)},`).join("\n");
|
|
670
|
+
const imports = [
|
|
671
|
+
usage.keyType ? `import type { I18nKey } from '${packageName}/engine';` : "",
|
|
672
|
+
usage.mergeKeys ? `import { mergeKeys } from '${packageName}/engine';` : "",
|
|
673
|
+
importLine
|
|
674
|
+
].filter(Boolean);
|
|
675
|
+
return [
|
|
676
|
+
GENERATED_HEADER("keys.generated.ts"),
|
|
677
|
+
LOCALES_REFERENCE,
|
|
678
|
+
"",
|
|
679
|
+
...imports,
|
|
680
|
+
"",
|
|
681
|
+
"/**",
|
|
682
|
+
" * Unified translation keys (TK) \u2014 one mental model.",
|
|
683
|
+
" * `TK.home.welcome` equals the literal key string `'home.welcome'`.",
|
|
684
|
+
" *",
|
|
685
|
+
" * Use in components with `translateSignal(TK.home.welcome)` and in templates",
|
|
686
|
+
" * via the generated typed directive (`{{ t.home.welcome() }}`).",
|
|
687
|
+
" */",
|
|
688
|
+
"export const TK = {",
|
|
689
|
+
body,
|
|
690
|
+
"} as const;",
|
|
691
|
+
"",
|
|
692
|
+
"/** Type of the TK object. */",
|
|
693
|
+
"export type TranslationKeys = typeof TK;",
|
|
694
|
+
""
|
|
695
|
+
].join("\n");
|
|
696
|
+
}
|
|
697
|
+
var LOCALES_REFERENCE = '/// <reference path="./i18n-locales.generated.d.ts" />';
|
|
698
|
+
function emitLocales(config) {
|
|
699
|
+
const fields = config.locales.map((locale) => ` ${propertyName2(locale)}: string;`);
|
|
700
|
+
return [
|
|
701
|
+
GENERATED_HEADER("i18n-locales.generated.d.ts"),
|
|
702
|
+
"",
|
|
703
|
+
`import '${config.packageName}/engine';`,
|
|
704
|
+
"",
|
|
705
|
+
`declare module '${config.packageName}/engine' {`,
|
|
706
|
+
" interface I18nLocales {",
|
|
707
|
+
...fields,
|
|
708
|
+
" }",
|
|
709
|
+
"}",
|
|
710
|
+
""
|
|
711
|
+
].join("\n");
|
|
712
|
+
}
|
|
713
|
+
function emitDirective(config) {
|
|
714
|
+
const sel = config.directiveSelector;
|
|
715
|
+
return [
|
|
716
|
+
GENERATED_HEADER(`${sel}.directive.ts`),
|
|
717
|
+
"",
|
|
718
|
+
`import { Directive, input } from '@angular/core';`,
|
|
719
|
+
`import { TranslateContext, TranslateDirectiveBase } from '${config.packageName}';`,
|
|
720
|
+
"",
|
|
721
|
+
`import { TK } from './keys.generated';`,
|
|
722
|
+
"",
|
|
723
|
+
"/**",
|
|
724
|
+
" * Typed structural translate directive. Extends the library base and pins",
|
|
725
|
+
" * the template context to this project's `typeof TK`, giving full",
|
|
726
|
+
" * autocomplete inside `*" + sel + '="let t"` templates.',
|
|
727
|
+
" */",
|
|
728
|
+
`@Directive({ selector: '[${sel}]' })`,
|
|
729
|
+
`export class ${config.directiveClassName} extends TranslateDirectiveBase {`,
|
|
730
|
+
" /**",
|
|
731
|
+
" * Optional prefix prepended to every key (for scoped translations).",
|
|
732
|
+
` * Microsyntax: \`*${sel}="let t; prefix: 'admin'"\` binds here.`,
|
|
733
|
+
" */",
|
|
734
|
+
` readonly ${sel}Prefix = input<string | undefined>(undefined);`,
|
|
735
|
+
"",
|
|
736
|
+
" protected override prefix(): string | undefined {",
|
|
737
|
+
` return this.${sel}Prefix();`,
|
|
738
|
+
" }",
|
|
739
|
+
"",
|
|
740
|
+
` static ngTemplateContextGuard(_dir: ${config.directiveClassName}, ctx: unknown): ctx is TranslateContext<typeof TK> {`,
|
|
741
|
+
" return true;",
|
|
742
|
+
" }",
|
|
743
|
+
"}",
|
|
744
|
+
""
|
|
745
|
+
].join("\n");
|
|
746
|
+
}
|
|
747
|
+
function GENERATED_HEADER(file) {
|
|
748
|
+
return [
|
|
749
|
+
"/**",
|
|
750
|
+
` * AUTO-GENERATED \u2014 do not edit by hand (${file}).`,
|
|
751
|
+
" *",
|
|
752
|
+
" * Produced by `hakistack-i18n scan`. Re-run the scan after adding,",
|
|
753
|
+
" * removing, or renaming a `*.i18n.ts` module. Safe to gitignore or commit.",
|
|
754
|
+
" */"
|
|
755
|
+
].join("\n");
|
|
756
|
+
}
|
|
757
|
+
function runScan(config, opts = {}) {
|
|
758
|
+
const { modules, issues } = discover(config);
|
|
759
|
+
const log = opts.quiet ? () => {
|
|
760
|
+
} : (m) => console.log(m);
|
|
761
|
+
const at = (loc) => formatLocation(loc, config.cwd);
|
|
762
|
+
const fail = (title, lines) => {
|
|
763
|
+
console.error(`
|
|
764
|
+
\u274C ${title}
|
|
765
|
+
${lines.map((l) => ` ${l}`).join("\n")}
|
|
766
|
+
No files were written.`);
|
|
767
|
+
process.exitCode = 1;
|
|
768
|
+
return { ok: false, moduleCount: modules.length, changed: [], missingScopes: [] };
|
|
769
|
+
};
|
|
770
|
+
printIssues(issues, at);
|
|
771
|
+
if (modules.length === 0) {
|
|
772
|
+
console.error(`\u274C No translation modules found under ${config.srcRoot} (expected at least one *.i18n.ts).`);
|
|
773
|
+
if (!opts.listOnly) process.exitCode = 1;
|
|
774
|
+
return { ok: !!opts.listOnly, moduleCount: 0, changed: [], missingScopes: [] };
|
|
775
|
+
}
|
|
776
|
+
log(`
|
|
777
|
+
\u{1F50D} i18n scan \u2014 discovered ${modules.length} module${modules.length === 1 ? "" : "s"}:`);
|
|
778
|
+
for (const mod of modules) {
|
|
779
|
+
log(` \u2022 ${mod.exportName}${mod.scope ? ` (${mod.scope})` : ""} \u2190 ${at({ file: mod.sourceFile, line: mod.line })}`);
|
|
780
|
+
}
|
|
781
|
+
const duplicateNames = findDuplicateExportNames(modules);
|
|
782
|
+
if (duplicateNames.length) {
|
|
783
|
+
return fail(
|
|
784
|
+
"Translation module names must be unique (they are imported side by side in the generated barrel). Rename one of the exports:",
|
|
785
|
+
duplicateNames.map(([name, mods]) => `${name}: ${mods.map((m) => at({ file: m.sourceFile, line: m.line })).join(", ")}`)
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
const conflicts = conflictsFromLeaves(modules.flatMap((m) => m.keys.map(({ key }) => ({ key, scope: m.scope ?? "" }))));
|
|
789
|
+
if (conflicts.length) {
|
|
790
|
+
const locations = keyLocations(modules);
|
|
791
|
+
return fail(
|
|
792
|
+
`${conflicts.length} key conflict(s):`,
|
|
793
|
+
conflicts.map((c) => describeConflict(c, locations.get(c.key)?.map(at)))
|
|
794
|
+
);
|
|
795
|
+
}
|
|
796
|
+
const missingScopes = modules.filter((m) => !m.scope).map((m) => m.exportName);
|
|
797
|
+
const { duplicateScopes } = buildTKTree(modules);
|
|
798
|
+
for (const [scope, names] of duplicateScopes) {
|
|
799
|
+
log(`
|
|
800
|
+
\u2139\uFE0E Scope '${scope}' is shared by ${names.join(", ")}; their keys are merged into TK${tkPath(scope)}.`);
|
|
801
|
+
}
|
|
802
|
+
if (opts.listOnly) {
|
|
803
|
+
log("\n\u2713 Listing only (--list); no files emitted.\n");
|
|
804
|
+
return { ok: true, moduleCount: modules.length, changed: [], missingScopes };
|
|
805
|
+
}
|
|
806
|
+
const result = syncOutputs(config.cwd, `scan:${config.definitionsDir}`, config.definitionsDir, [
|
|
807
|
+
{ file: path5.join(config.definitionsDir, "index.generated.ts"), content: emitBarrel(modules) },
|
|
808
|
+
{ file: path5.join(config.definitionsDir, "keys.generated.ts"), content: emitKeys(modules, config.packageName) },
|
|
809
|
+
{ file: path5.join(config.definitionsDir, `${config.directiveSelector}.directive.ts`), content: emitDirective(config) },
|
|
810
|
+
{ file: path5.join(config.definitionsDir, "i18n-locales.generated.d.ts"), content: emitLocales(config) }
|
|
811
|
+
]);
|
|
812
|
+
const rel = (f) => path5.relative(config.cwd, f);
|
|
813
|
+
const changed = [...result.written, ...result.removed].map(rel);
|
|
814
|
+
if (result.written.length) log(`
|
|
815
|
+
\u2713 Wrote:
|
|
816
|
+
${result.written.map((f) => ` ${rel(f)}`).join("\n")}`);
|
|
817
|
+
if (result.removed.length) log(`
|
|
818
|
+
\u2713 Removed stale:
|
|
819
|
+
${result.removed.map((f) => ` ${rel(f)}`).join("\n")}`);
|
|
820
|
+
log(changed.length ? "" : "\n\u2713 Up to date \u2014 no changes.\n");
|
|
821
|
+
return { ok: true, moduleCount: modules.length, changed, missingScopes };
|
|
822
|
+
}
|
|
823
|
+
function printIssues(issues, at) {
|
|
824
|
+
for (const issue of issues) {
|
|
825
|
+
const line = `${issue.severity === "error" ? "\u274C" : "\u26A0\uFE0F "} ${at(issue)} \u2014 ${issue.message}`;
|
|
826
|
+
if (issue.severity === "error") console.error(line);
|
|
827
|
+
else console.warn(line);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
function tkPath(scope) {
|
|
831
|
+
return scope.split(".").map((part) => IDENTIFIER_RE.test(part) ? `.${part}` : `['${part}']`).join("");
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// projects/hakistack/i18n/cli/validate.ts
|
|
835
|
+
function extractPlaceholders(text) {
|
|
836
|
+
return (text.match(/\{\{[^}]+}}/g) || []).map((p) => `{{${p.slice(2, -2).trim()}}}`).sort();
|
|
837
|
+
}
|
|
838
|
+
function arraysEqual(a, b) {
|
|
839
|
+
return a.length === b.length && a.every((v, i) => v === b[i]);
|
|
840
|
+
}
|
|
841
|
+
function validateNode(obj, moduleName, locales, defaultLang, errors, stubs, keyPath = []) {
|
|
842
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
843
|
+
const currentPath = [...keyPath, key];
|
|
844
|
+
const fullKey = currentPath.join(".");
|
|
845
|
+
if (isTranslationValue(value)) {
|
|
846
|
+
const byLang = value;
|
|
847
|
+
const source = byLang[defaultLang];
|
|
848
|
+
if (!source || source.trim() === "") {
|
|
849
|
+
errors.push({
|
|
850
|
+
module: moduleName,
|
|
851
|
+
key: fullKey,
|
|
852
|
+
language: defaultLang,
|
|
853
|
+
issue: `Missing or empty required ${defaultLang} translation`,
|
|
854
|
+
severity: "error"
|
|
855
|
+
});
|
|
856
|
+
continue;
|
|
857
|
+
}
|
|
858
|
+
const srcPlaceholders = extractPlaceholders(source);
|
|
859
|
+
const srcHasPlaceholders = srcPlaceholders.length > 0;
|
|
860
|
+
let hasAnyOtherLocale = false;
|
|
861
|
+
for (const lang of locales) {
|
|
862
|
+
if (lang === defaultLang) continue;
|
|
863
|
+
const translation = byLang[lang];
|
|
864
|
+
if (!translation) {
|
|
865
|
+
errors.push({
|
|
866
|
+
module: moduleName,
|
|
867
|
+
key: fullKey,
|
|
868
|
+
language: lang,
|
|
869
|
+
issue: srcHasPlaceholders ? `Missing translation for placeholder string. Strings containing {{\u2026}} require parity in every locale.` : "Missing translation (will fallback)",
|
|
870
|
+
severity: srcHasPlaceholders ? "error" : "warning"
|
|
871
|
+
});
|
|
872
|
+
continue;
|
|
873
|
+
}
|
|
874
|
+
hasAnyOtherLocale = true;
|
|
875
|
+
if (translation.trim() === "") {
|
|
876
|
+
errors.push({ module: moduleName, key: fullKey, language: lang, issue: "Empty translation value", severity: "error" });
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
const langPlaceholders = extractPlaceholders(translation);
|
|
880
|
+
if (!arraysEqual(srcPlaceholders, langPlaceholders)) {
|
|
881
|
+
errors.push({
|
|
882
|
+
module: moduleName,
|
|
883
|
+
key: fullKey,
|
|
884
|
+
language: lang,
|
|
885
|
+
issue: `Placeholder mismatch. ${defaultLang.toUpperCase()}: [${srcPlaceholders.join(", ")}] | ${lang.toUpperCase()}: [${langPlaceholders.join(", ")}]`,
|
|
886
|
+
severity: "error"
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (!hasAnyOtherLocale && locales.length > 1) {
|
|
891
|
+
stubs.push({ module: moduleName, key: fullKey });
|
|
892
|
+
}
|
|
893
|
+
} else if (typeof value === "object" && value !== null) {
|
|
894
|
+
validateNode(value, moduleName, locales, defaultLang, errors, stubs, currentPath);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
async function runValidate(config, opts = {}) {
|
|
899
|
+
const info = opts.quiet ? () => void 0 : (m) => console.log(m);
|
|
900
|
+
info("\n\u{1F50D} i18n validation\n" + "=".repeat(50));
|
|
901
|
+
const registry = await loadRegistry(config);
|
|
902
|
+
const locate = createKeyLocator(config);
|
|
903
|
+
const conflicts = findKeyConflicts(registry);
|
|
904
|
+
if (conflicts.length) {
|
|
905
|
+
console.log(`
|
|
906
|
+
\u274C ${conflicts.length} key conflict(s):
|
|
907
|
+
`);
|
|
908
|
+
for (const c of conflicts) console.log(` ${describeConflict(c, locate(c.key))}`);
|
|
909
|
+
console.log("\n\u274C Validation failed!\n");
|
|
910
|
+
process.exitCode = 1;
|
|
911
|
+
return false;
|
|
912
|
+
}
|
|
913
|
+
const errors = [];
|
|
914
|
+
const stubs = [];
|
|
915
|
+
for (const mod of registry) {
|
|
916
|
+
validateNode(mod.translations, mod.scope, config.locales, SOURCE_LANG, errors, stubs);
|
|
917
|
+
}
|
|
918
|
+
const actualErrors = errors.filter((e) => e.severity === "error");
|
|
919
|
+
const warnings = errors.filter((e) => e.severity === "warning");
|
|
920
|
+
if (actualErrors.length === 0 && warnings.length === 0 && stubs.length === 0) {
|
|
921
|
+
info("\n\u2713 All translations are valid!\n");
|
|
922
|
+
return true;
|
|
923
|
+
}
|
|
924
|
+
if (actualErrors.length) {
|
|
925
|
+
console.log(`
|
|
926
|
+
\u274C ${actualErrors.length} error(s):
|
|
927
|
+
`);
|
|
928
|
+
for (const e of actualErrors) {
|
|
929
|
+
const where = locate(`${e.module}.${e.key}`)[0];
|
|
930
|
+
console.log(` [${e.module}] ${e.key} (${e.language.toUpperCase()})
|
|
931
|
+
\u2192 ${e.issue}${where ? `
|
|
932
|
+
at ${where}` : ""}`);
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (warnings.length) {
|
|
936
|
+
info(`
|
|
937
|
+
\u26A0\uFE0F ${warnings.length} warning(s):
|
|
938
|
+
`);
|
|
939
|
+
const byLang = {};
|
|
940
|
+
for (const w of warnings) (byLang[w.language] ??= []).push(w);
|
|
941
|
+
for (const [lang, list] of Object.entries(byLang)) {
|
|
942
|
+
info(` ${lang.toUpperCase()}: ${list.length} missing`);
|
|
943
|
+
for (const w of list.slice(0, 5)) info(` - ${w.key}`);
|
|
944
|
+
if (list.length > 5) info(` \u2026 and ${list.length - 5} more`);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
if (stubs.length) {
|
|
948
|
+
info(`
|
|
949
|
+
\u{1F4DD} Stub report \u2014 ${stubs.length} source-only ${stubs.length === 1 ? "leaf" : "leaves"}:
|
|
950
|
+
`);
|
|
951
|
+
const byModule = {};
|
|
952
|
+
for (const s of stubs) (byModule[s.module] ??= []).push(s.key);
|
|
953
|
+
for (const [moduleName, keys] of Object.entries(byModule)) {
|
|
954
|
+
info(` ${moduleName}: ${keys.length}`);
|
|
955
|
+
for (const k of keys.slice(0, 5)) info(` - ${k}`);
|
|
956
|
+
if (keys.length > 5) info(` \u2026 and ${keys.length - 5} more`);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
info(`
|
|
960
|
+
\u{1F4CA} Summary
|
|
961
|
+
Errors: ${actualErrors.length} Warnings: ${warnings.length} Stubs: ${stubs.length}`);
|
|
962
|
+
if (actualErrors.length) {
|
|
963
|
+
console.log("\n\u274C Validation failed!\n");
|
|
964
|
+
process.exitCode = 1;
|
|
965
|
+
return false;
|
|
966
|
+
}
|
|
967
|
+
info("\n\u2713 Validation passed.\n");
|
|
968
|
+
return true;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// projects/hakistack/i18n/cli/check.ts
|
|
972
|
+
async function runCheck(config, opts = {}) {
|
|
973
|
+
if (!runScan(config, { quiet: opts.quiet }).ok) return false;
|
|
974
|
+
if (!await runValidate(config, opts)) return false;
|
|
975
|
+
return runGenerate(config, opts);
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
// projects/hakistack/i18n/cli/config.ts
|
|
979
|
+
var fs4 = __toESM(require("fs"));
|
|
980
|
+
var path6 = __toESM(require("path"));
|
|
981
|
+
var import_jiti2 = require("jiti");
|
|
982
|
+
var CONFIG_BASENAMES = [
|
|
983
|
+
"i18n.config.ts",
|
|
984
|
+
"i18n.config.mts",
|
|
985
|
+
"i18n.config.cts",
|
|
986
|
+
"i18n.config.js",
|
|
987
|
+
"i18n.config.mjs",
|
|
988
|
+
"i18n.config.cjs",
|
|
989
|
+
"i18n.config.json"
|
|
990
|
+
];
|
|
991
|
+
var DEFAULTS = {
|
|
992
|
+
srcRoot: "src",
|
|
993
|
+
definitionsDir: "src/i18n/definitions",
|
|
994
|
+
outputDir: "src/assets/i18n",
|
|
995
|
+
locales: ["en"],
|
|
996
|
+
packageName: "@hakistack/i18n",
|
|
997
|
+
directiveSelector: "appTranslate",
|
|
998
|
+
directiveClassName: "AppTranslateDirective"
|
|
999
|
+
};
|
|
1000
|
+
function findConfigFile(cwd) {
|
|
1001
|
+
for (const basename2 of CONFIG_BASENAMES) {
|
|
1002
|
+
const candidate = path6.join(cwd, basename2);
|
|
1003
|
+
if (fs4.existsSync(candidate)) return candidate;
|
|
1004
|
+
}
|
|
1005
|
+
return null;
|
|
1006
|
+
}
|
|
1007
|
+
async function loadConfig(cwd, overrides = {}) {
|
|
1008
|
+
let fileConfig = {};
|
|
1009
|
+
const configPath = findConfigFile(cwd);
|
|
1010
|
+
if (configPath) {
|
|
1011
|
+
if (configPath.endsWith(".json")) {
|
|
1012
|
+
fileConfig = JSON.parse(fs4.readFileSync(configPath, "utf-8"));
|
|
1013
|
+
} else {
|
|
1014
|
+
const jiti = (0, import_jiti2.createJiti)(__filename);
|
|
1015
|
+
const mod = await jiti.import(configPath);
|
|
1016
|
+
fileConfig = mod.default ?? mod;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
const legacySourceLang = fileConfig.sourceLang;
|
|
1020
|
+
if (legacySourceLang !== void 0 && legacySourceLang !== SOURCE_LANG) {
|
|
1021
|
+
throw new Error(
|
|
1022
|
+
`i18n: 'sourceLang' is not configurable \u2014 the source locale is always '${SOURCE_LANG}' (t()'s first argument). Remove 'sourceLang' from ${configPath ?? "the config"}.`
|
|
1023
|
+
);
|
|
1024
|
+
}
|
|
1025
|
+
const merged = { ...DEFAULTS, ...stripUndefined(fileConfig), ...stripUndefined(overrides) };
|
|
1026
|
+
const requested = merged.locales && merged.locales.length > 0 ? merged.locales : DEFAULTS.locales;
|
|
1027
|
+
const locales = requested.includes(SOURCE_LANG) ? requested : [SOURCE_LANG, ...requested];
|
|
1028
|
+
return {
|
|
1029
|
+
cwd,
|
|
1030
|
+
srcRoot: path6.resolve(cwd, merged.srcRoot),
|
|
1031
|
+
definitionsDir: path6.resolve(cwd, merged.definitionsDir),
|
|
1032
|
+
outputDir: path6.resolve(cwd, merged.outputDir),
|
|
1033
|
+
locales,
|
|
1034
|
+
sourceLang: SOURCE_LANG,
|
|
1035
|
+
packageName: merged.packageName,
|
|
1036
|
+
directiveSelector: merged.directiveSelector,
|
|
1037
|
+
directiveClassName: merged.directiveClassName
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
function stripUndefined(obj) {
|
|
1041
|
+
const out = {};
|
|
1042
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
1043
|
+
if (v !== void 0) out[k] = v;
|
|
1044
|
+
}
|
|
1045
|
+
return out;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// projects/hakistack/i18n/cli/find-unused.ts
|
|
1049
|
+
var fs5 = __toESM(require("fs"));
|
|
1050
|
+
var path7 = __toESM(require("path"));
|
|
1051
|
+
var EXCLUDED_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "out-tsc", ".angular", ".cache"]);
|
|
1052
|
+
var TEST_FILE_RE = /\.spec\.ts$/;
|
|
1053
|
+
var SKIPPED_FILE_RE = /\.i18n\.ts$|\.generated\.ts$|\.d\.ts$/;
|
|
1054
|
+
var SCANNABLE_RE = /\.(ts|html)$/;
|
|
1055
|
+
var MARKER_RE = /\/\*\s*i18n-used:\s*([\s\S]+?)\s*\*\//g;
|
|
1056
|
+
function escapeRegex(s) {
|
|
1057
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1058
|
+
}
|
|
1059
|
+
function* walkSourceFiles(dir) {
|
|
1060
|
+
if (!fs5.existsSync(dir)) return;
|
|
1061
|
+
for (const entry of fs5.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1062
|
+
if (entry.name.startsWith(".") || EXCLUDED_DIRS.has(entry.name)) continue;
|
|
1063
|
+
const full = path7.join(dir, entry.name);
|
|
1064
|
+
if (entry.isDirectory()) yield* walkSourceFiles(full);
|
|
1065
|
+
else if (entry.isFile() && SCANNABLE_RE.test(entry.name) && !SKIPPED_FILE_RE.test(entry.name)) yield full;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
function lineAt(text, index) {
|
|
1069
|
+
let line = 1;
|
|
1070
|
+
for (let i = 0; i < index; i++) if (text.charCodeAt(i) === 10) line++;
|
|
1071
|
+
return line;
|
|
1072
|
+
}
|
|
1073
|
+
function patternToRegex(claimed) {
|
|
1074
|
+
return new RegExp("^" + claimed.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
|
|
1075
|
+
}
|
|
1076
|
+
function resolveTK(tk, segments) {
|
|
1077
|
+
let node = tk;
|
|
1078
|
+
for (const s of segments) {
|
|
1079
|
+
if (!node || typeof node !== "object") return void 0;
|
|
1080
|
+
node = node[s];
|
|
1081
|
+
}
|
|
1082
|
+
return node;
|
|
1083
|
+
}
|
|
1084
|
+
function leavesOf(node, out = []) {
|
|
1085
|
+
if (typeof node === "string") out.push(node);
|
|
1086
|
+
else if (node && typeof node === "object") for (const v of Object.values(node)) leavesOf(v, out);
|
|
1087
|
+
return out;
|
|
1088
|
+
}
|
|
1089
|
+
async function runFindUnused(config, opts = {}) {
|
|
1090
|
+
const registry = await loadRegistry(config);
|
|
1091
|
+
const tk = await loadKeys(config);
|
|
1092
|
+
const ts = loadTypeScript(config.cwd);
|
|
1093
|
+
const print = opts.quiet ? () => void 0 : (m) => console.log(m);
|
|
1094
|
+
const status = /* @__PURE__ */ new Map();
|
|
1095
|
+
for (const mod of registry) {
|
|
1096
|
+
for (const key of leavesOf(mod.keys)) status.set(key, { key, confirmed: [], potential: [], test: [], claimed: false });
|
|
1097
|
+
}
|
|
1098
|
+
const sortedKeys = [...status.keys()].sort();
|
|
1099
|
+
for (const file of walkSourceFiles(config.srcRoot)) {
|
|
1100
|
+
const text = fs5.readFileSync(file, "utf-8");
|
|
1101
|
+
const ref = (index) => ({ file: path7.relative(config.cwd, file), line: lineAt(text, index) });
|
|
1102
|
+
const isTest = TEST_FILE_RE.test(file);
|
|
1103
|
+
const confirm = (key, at) => {
|
|
1104
|
+
const st = status.get(key);
|
|
1105
|
+
if (st) (isTest ? st.test : st.confirmed).push(at);
|
|
1106
|
+
};
|
|
1107
|
+
const maybe = (keys, at) => {
|
|
1108
|
+
for (const key of keys) {
|
|
1109
|
+
const st = status.get(key);
|
|
1110
|
+
if (st) (isTest ? st.test : st.potential).push(at);
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
const underPrefix = (prefix) => sortedKeys.filter((k) => k.startsWith(prefix));
|
|
1114
|
+
const literal = (value, at, translateArg = false) => {
|
|
1115
|
+
if (status.has(value)) confirm(value, at);
|
|
1116
|
+
else if (value.length > 1 && value.endsWith(".")) maybe(underPrefix(value), at);
|
|
1117
|
+
else if (/^[\w$-]+(\.[\w$-]+)*$/.test(value) && (value.includes(".") || translateArg)) maybe(underPrefix(`${value}.`), at);
|
|
1118
|
+
};
|
|
1119
|
+
for (const m of text.matchAll(MARKER_RE)) {
|
|
1120
|
+
const pattern = patternToRegex(m[1].trim());
|
|
1121
|
+
for (const st of status.values()) if (pattern.test(st.key)) st.claimed = true;
|
|
1122
|
+
}
|
|
1123
|
+
if (file.endsWith(".html")) {
|
|
1124
|
+
scanTemplate(text, 0, config.directiveSelector, { tk, ref, confirm, maybe, literal, underPrefix });
|
|
1125
|
+
continue;
|
|
1126
|
+
}
|
|
1127
|
+
scanTypeScript(ts, file, text, { tk, ref, confirm, maybe, literal, underPrefix, directiveSelector: config.directiveSelector });
|
|
1128
|
+
}
|
|
1129
|
+
const usage = /* @__PURE__ */ new Map();
|
|
1130
|
+
for (const st of status.values()) {
|
|
1131
|
+
usage.set(
|
|
1132
|
+
st.key,
|
|
1133
|
+
st.claimed ? "claimed" : st.confirmed.length ? "used" : st.potential.length ? "possibly-used" : st.test.length ? "test-only" : "unused"
|
|
1134
|
+
);
|
|
1135
|
+
}
|
|
1136
|
+
report(status, usage, print, opts);
|
|
1137
|
+
if (opts.strict && [...usage.values()].includes("unused")) {
|
|
1138
|
+
print("\u274C --strict: failing because unused keys were found.\n");
|
|
1139
|
+
process.exitCode = 1;
|
|
1140
|
+
}
|
|
1141
|
+
return { usage };
|
|
1142
|
+
}
|
|
1143
|
+
function touchTK(ctx, segments, dynamicTail, at) {
|
|
1144
|
+
const node = resolveTK(ctx.tk, segments);
|
|
1145
|
+
if (typeof node === "string" && !dynamicTail) ctx.confirm(node, at);
|
|
1146
|
+
else if (node && typeof node === "object") ctx.maybe(leavesOf(node), at);
|
|
1147
|
+
}
|
|
1148
|
+
function scanTypeScript(ts, file, text, ctx) {
|
|
1149
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
1150
|
+
const roots = /* @__PURE__ */ new Map([["TK", []]]);
|
|
1151
|
+
for (const stmt of sf.statements) {
|
|
1152
|
+
const bindings = ts.isImportDeclaration(stmt) ? stmt.importClause?.namedBindings : void 0;
|
|
1153
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
1154
|
+
for (const el of bindings.elements) if ((el.propertyName ?? el.name).text === "TK") roots.set(el.name.text, []);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
const chainOf = (node) => {
|
|
1158
|
+
const segments = [];
|
|
1159
|
+
let dynamicTail = false;
|
|
1160
|
+
let current = node;
|
|
1161
|
+
for (; ; ) {
|
|
1162
|
+
if (ts.isPropertyAccessExpression(current)) {
|
|
1163
|
+
segments.unshift(current.name.text);
|
|
1164
|
+
current = current.expression;
|
|
1165
|
+
} else if (ts.isElementAccessExpression(current)) {
|
|
1166
|
+
const arg = current.argumentExpression;
|
|
1167
|
+
if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) segments.unshift(arg.text);
|
|
1168
|
+
else {
|
|
1169
|
+
segments.length = 0;
|
|
1170
|
+
dynamicTail = true;
|
|
1171
|
+
}
|
|
1172
|
+
current = current.expression;
|
|
1173
|
+
} else if (ts.isNonNullExpression(current) || ts.isParenthesizedExpression(current)) {
|
|
1174
|
+
current = current.expression;
|
|
1175
|
+
} else break;
|
|
1176
|
+
}
|
|
1177
|
+
if (!ts.isIdentifier(current) || !roots.has(current.text)) return null;
|
|
1178
|
+
return { segments: [...roots.get(current.text), ...segments], dynamicTail };
|
|
1179
|
+
};
|
|
1180
|
+
const visit = (node) => {
|
|
1181
|
+
const at = () => ctx.ref(node.getStart(sf));
|
|
1182
|
+
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
|
|
1183
|
+
const chain = chainOf(node.initializer);
|
|
1184
|
+
if (chain && !chain.dynamicTail) roots.set(node.name.text, chain.segments);
|
|
1185
|
+
}
|
|
1186
|
+
if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) || ts.isIdentifier(node)) {
|
|
1187
|
+
const parent = node.parent;
|
|
1188
|
+
const isOutermost = !(parent && (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === node);
|
|
1189
|
+
const isDeclarationName = parent && (ts.isVariableDeclaration(parent) || ts.isImportSpecifier(parent)) && parent.name === node;
|
|
1190
|
+
if (isOutermost && !isDeclarationName) {
|
|
1191
|
+
const chain = chainOf(node);
|
|
1192
|
+
if (chain && (chain.segments.length > 0 || chain.dynamicTail)) touchTK(ctx, chain.segments, chain.dynamicTail, at());
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
|
|
1196
|
+
const call = node.parent;
|
|
1197
|
+
const translateArg = !!call && ts.isCallExpression(call) && /translate/i.test(call.expression.getText(sf));
|
|
1198
|
+
ctx.literal(node.text, at(), translateArg);
|
|
1199
|
+
if (isInlineTemplate(ts, node)) scanTemplate(node.text, node.getStart(sf) + 1, ctx.directiveSelector, ctx);
|
|
1200
|
+
}
|
|
1201
|
+
if (ts.isTemplateExpression(node)) {
|
|
1202
|
+
const head = node.head.text;
|
|
1203
|
+
if (head.length > 1 && head.endsWith(".")) ctx.maybe(ctx.underPrefix(head), at());
|
|
1204
|
+
if (isInlineTemplate(ts, node)) scanTemplate(node.getText(sf).slice(1, -1), node.getStart(sf) + 1, ctx.directiveSelector, ctx);
|
|
1205
|
+
}
|
|
1206
|
+
ts.forEachChild(node, visit);
|
|
1207
|
+
};
|
|
1208
|
+
visit(sf);
|
|
1209
|
+
}
|
|
1210
|
+
function isInlineTemplate(ts, node) {
|
|
1211
|
+
const parent = node.parent;
|
|
1212
|
+
return !!parent && ts.isPropertyAssignment(parent) && ts.isIdentifier(parent.name) && parent.name.text === "template";
|
|
1213
|
+
}
|
|
1214
|
+
function scanTemplate(template, offset, selector, ctx) {
|
|
1215
|
+
const html = template.replace(/<!--[\s\S]*?-->/g, (c) => " ".repeat(c.length));
|
|
1216
|
+
const at = (index) => ctx.ref(offset + index);
|
|
1217
|
+
const directiveRe = new RegExp(`\\*${escapeRegex(selector)}\\s*=\\s*"([^"]*)"`, "g");
|
|
1218
|
+
const contexts = /* @__PURE__ */ new Map();
|
|
1219
|
+
for (const m of html.matchAll(directiveRe)) {
|
|
1220
|
+
const micro = m[1];
|
|
1221
|
+
const variable = /\blet\s+([A-Za-z_$][\w$]*)(?!\s*=)/.exec(micro)?.[1];
|
|
1222
|
+
const prefix = /\bprefix\s*:\s*'([^']*)'/.exec(micro)?.[1];
|
|
1223
|
+
if (variable) contexts.set(variable, prefix ? prefix.split(".") : []);
|
|
1224
|
+
}
|
|
1225
|
+
for (const [variable, prefix] of contexts) {
|
|
1226
|
+
const re = new RegExp(`(?<![\\w$.])${escapeRegex(variable)}((?:\\.[A-Za-z_$][\\w$]*)+)(\\s*\\[)?`, "g");
|
|
1227
|
+
for (const m of html.matchAll(re)) {
|
|
1228
|
+
touchTK(ctx, [...prefix, ...m[1].slice(1).split(".")], !!m[2], at(m.index ?? 0));
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
for (const m of html.matchAll(/'([^'\s<>{}]+)'|"([^"\s<>{}]+)"/g)) ctx.literal(m[1] ?? m[2], at(m.index ?? 0));
|
|
1232
|
+
}
|
|
1233
|
+
function report(status, usage, print, opts) {
|
|
1234
|
+
const by = (u) => [...usage].filter(([, v]) => v === u).map(([k]) => k).sort();
|
|
1235
|
+
const unused = by("unused");
|
|
1236
|
+
const possibly = by("possibly-used");
|
|
1237
|
+
const testOnly = by("test-only");
|
|
1238
|
+
const show = (title, keys, refs) => {
|
|
1239
|
+
if (!keys.length) return;
|
|
1240
|
+
print(`
|
|
1241
|
+
${title} (${keys.length}):
|
|
1242
|
+
`);
|
|
1243
|
+
for (const key of keys) {
|
|
1244
|
+
print(` ${key}`);
|
|
1245
|
+
if (opts.verbose) for (const r of refs(status.get(key)).slice(0, 3)) print(` ${r.file}:${r.line}`);
|
|
1246
|
+
}
|
|
1247
|
+
};
|
|
1248
|
+
print("\n\u{1F50D} i18n unused-key detector\n" + "=".repeat(50));
|
|
1249
|
+
show("\u274C Unused", unused, () => []);
|
|
1250
|
+
show("\u2754 Possibly used \u2014 only dynamic references (group values, key prefixes); never reported as unused", possibly, (st) => st.potential);
|
|
1251
|
+
show("\u26A0\uFE0F Test-only \u2014 referenced ONLY in *.spec.ts", testOnly, (st) => st.test);
|
|
1252
|
+
print(
|
|
1253
|
+
`
|
|
1254
|
+
\u{1F4CA} Summary
|
|
1255
|
+
Total: ${usage.size} Used: ${by("used").length} Possibly used: ${possibly.length} Test-only: ${testOnly.length} Claimed: ${by("claimed").length} Unused: ${unused.length}
|
|
1256
|
+
`
|
|
1257
|
+
);
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
// projects/hakistack/i18n/cli/watch.ts
|
|
1261
|
+
var path8 = __toESM(require("path"));
|
|
1262
|
+
var import_jiti3 = require("jiti");
|
|
1263
|
+
async function runWatch(config) {
|
|
1264
|
+
let chokidar;
|
|
1265
|
+
try {
|
|
1266
|
+
const mod = await (0, import_jiti3.createJiti)(__filename).import("chokidar");
|
|
1267
|
+
chokidar = mod.default ?? mod;
|
|
1268
|
+
} catch {
|
|
1269
|
+
console.error('i18n watch requires the optional dependency "chokidar". Install it with:\n npm i -D chokidar');
|
|
1270
|
+
process.exitCode = 1;
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
1273
|
+
await runCycle(config);
|
|
1274
|
+
console.log(`[i18n-watch] watching ${path8.relative(config.cwd, config.srcRoot)}/**/*${I18N_SUFFIX}`);
|
|
1275
|
+
let running = false;
|
|
1276
|
+
let pending = false;
|
|
1277
|
+
const trigger = async (label) => {
|
|
1278
|
+
if (running) {
|
|
1279
|
+
pending = true;
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
running = true;
|
|
1283
|
+
console.log(`[i18n-watch] ${label}`);
|
|
1284
|
+
try {
|
|
1285
|
+
await runCycle(config);
|
|
1286
|
+
} finally {
|
|
1287
|
+
running = false;
|
|
1288
|
+
if (pending) {
|
|
1289
|
+
pending = false;
|
|
1290
|
+
void trigger("more changes");
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
const watcher = chokidar.watch(config.srcRoot, {
|
|
1295
|
+
ignoreInitial: true,
|
|
1296
|
+
awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 30 },
|
|
1297
|
+
ignored: (p, stats) => {
|
|
1298
|
+
const base = path8.basename(p);
|
|
1299
|
+
if (base === "node_modules" || base.startsWith(".")) return true;
|
|
1300
|
+
if (stats?.isFile()) return !p.endsWith(I18N_SUFFIX);
|
|
1301
|
+
return false;
|
|
1302
|
+
}
|
|
1303
|
+
});
|
|
1304
|
+
watcher.on("add", (p) => void trigger(`add ${path8.relative(config.cwd, p)}`)).on("unlink", (p) => void trigger(`remove ${path8.relative(config.cwd, p)}`)).on("change", (p) => void trigger(`change ${path8.relative(config.cwd, p)}`));
|
|
1305
|
+
const shutdown = () => watcher.close().then(() => process.exit(0));
|
|
1306
|
+
process.on("SIGINT", shutdown);
|
|
1307
|
+
process.on("SIGTERM", shutdown);
|
|
1308
|
+
}
|
|
1309
|
+
async function runCycle(config) {
|
|
1310
|
+
try {
|
|
1311
|
+
const ok = await runCheck(config, { quiet: true });
|
|
1312
|
+
if (ok) console.log("[i18n-watch] \u2713 up to date");
|
|
1313
|
+
} catch (err) {
|
|
1314
|
+
console.error(`[i18n-watch] ${err instanceof Error ? err.message : String(err)}`);
|
|
1315
|
+
} finally {
|
|
1316
|
+
process.exitCode = 0;
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// projects/hakistack/i18n/cli/bin.ts
|
|
1321
|
+
function parseArgs(argv) {
|
|
1322
|
+
const command = argv[0] ?? "help";
|
|
1323
|
+
const flags = {};
|
|
1324
|
+
for (let i = 1; i < argv.length; i++) {
|
|
1325
|
+
const arg = argv[i];
|
|
1326
|
+
if (!arg.startsWith("--")) continue;
|
|
1327
|
+
const key = arg.slice(2);
|
|
1328
|
+
const next = argv[i + 1];
|
|
1329
|
+
if (next !== void 0 && !next.startsWith("--")) {
|
|
1330
|
+
flags[key] = next;
|
|
1331
|
+
i++;
|
|
1332
|
+
} else {
|
|
1333
|
+
flags[key] = true;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
return { command, flags };
|
|
1337
|
+
}
|
|
1338
|
+
function configOverrides(flags) {
|
|
1339
|
+
const o = {};
|
|
1340
|
+
if (typeof flags["src-root"] === "string") o.srcRoot = flags["src-root"];
|
|
1341
|
+
if (typeof flags["definitions-dir"] === "string") o.definitionsDir = flags["definitions-dir"];
|
|
1342
|
+
if (typeof flags["output-dir"] === "string") o.outputDir = flags["output-dir"];
|
|
1343
|
+
if (typeof flags["locales"] === "string")
|
|
1344
|
+
o.locales = flags["locales"].split(",").map((s) => s.trim()).filter(Boolean);
|
|
1345
|
+
return o;
|
|
1346
|
+
}
|
|
1347
|
+
var HELP = `hakistack-i18n \u2014 type-safe i18n codegen
|
|
1348
|
+
|
|
1349
|
+
Usage: hakistack-i18n <command> [flags]
|
|
1350
|
+
|
|
1351
|
+
Commands:
|
|
1352
|
+
check scan + validate + generate \u2014 the everyday command (prebuild, CI)
|
|
1353
|
+
scan Discover *.i18n.ts and emit barrel + TK literal + typed directive
|
|
1354
|
+
generate Write JSON translation files
|
|
1355
|
+
validate Gate on missing / placeholder-mismatched translations
|
|
1356
|
+
find-unused Report defined keys with no references
|
|
1357
|
+
watch Re-run scan + validate + generate on *.i18n.ts changes
|
|
1358
|
+
|
|
1359
|
+
Flags:
|
|
1360
|
+
--config <path> Explicit config file
|
|
1361
|
+
--src-root <dir> Directory scanned for *.i18n.ts
|
|
1362
|
+
--definitions-dir <d> Where generated files land
|
|
1363
|
+
--output-dir <dir> JSON output directory
|
|
1364
|
+
--locales <a,b,c> Comma-separated locale ids (en is always included)
|
|
1365
|
+
--list (scan) list modules without emitting
|
|
1366
|
+
--strict (find-unused) exit 1 if unused keys exist
|
|
1367
|
+
--verbose (find-unused) print reference locations
|
|
1368
|
+
--quiet (check) print changes and errors only
|
|
1369
|
+
`;
|
|
1370
|
+
async function main() {
|
|
1371
|
+
const { command, flags } = parseArgs(process.argv.slice(2));
|
|
1372
|
+
if (command === "help" || command === "--help" || command === "-h") {
|
|
1373
|
+
console.log(HELP);
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
const cwd = process.cwd();
|
|
1377
|
+
const overrides = configOverrides(flags);
|
|
1378
|
+
if (typeof flags["config"] === "string") {
|
|
1379
|
+
process.chdir(path9.dirname(path9.resolve(cwd, flags["config"])));
|
|
1380
|
+
}
|
|
1381
|
+
const config = await loadConfig(process.cwd(), overrides);
|
|
1382
|
+
switch (command) {
|
|
1383
|
+
case "check":
|
|
1384
|
+
await runCheck(config, { quiet: flags["quiet"] === true });
|
|
1385
|
+
break;
|
|
1386
|
+
case "scan":
|
|
1387
|
+
runScan(config, { listOnly: flags["list"] === true });
|
|
1388
|
+
break;
|
|
1389
|
+
case "generate":
|
|
1390
|
+
await runGenerate(config);
|
|
1391
|
+
break;
|
|
1392
|
+
case "validate":
|
|
1393
|
+
await runValidate(config);
|
|
1394
|
+
break;
|
|
1395
|
+
case "find-unused":
|
|
1396
|
+
await runFindUnused(config, { strict: flags["strict"] === true, verbose: flags["verbose"] === true });
|
|
1397
|
+
break;
|
|
1398
|
+
case "watch":
|
|
1399
|
+
await runWatch(config);
|
|
1400
|
+
break;
|
|
1401
|
+
default:
|
|
1402
|
+
console.error(`Unknown command: ${command}
|
|
1403
|
+
`);
|
|
1404
|
+
console.log(HELP);
|
|
1405
|
+
process.exitCode = 1;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
main().catch((err) => {
|
|
1409
|
+
console.error(err instanceof Error ? err.message : err);
|
|
1410
|
+
process.exitCode = 1;
|
|
1411
|
+
});
|