@hakistack/i18n 0.1.0 → 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/cli/bin.cjs CHANGED
@@ -24,12 +24,38 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
  ));
25
25
 
26
26
  // projects/hakistack/i18n/cli/bin.ts
27
- var path7 = __toESM(require("path"));
27
+ var path9 = __toESM(require("path"));
28
28
 
29
- // projects/hakistack/i18n/cli/config.ts
30
- var fs = __toESM(require("fs"));
31
- var path = __toESM(require("path"));
32
- var import_jiti = require("jiti");
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
+ }
33
59
 
34
60
  // projects/hakistack/i18n/engine/define-translations.ts
35
61
  var SOURCE_LANG = "en";
@@ -37,90 +63,97 @@ var TRANSLATION_BRAND = /* @__PURE__ */ Symbol.for("@hakistack/i18n:translation-
37
63
  function isTranslationValue(value) {
38
64
  return value !== null && typeof value === "object" && value[TRANSLATION_BRAND] === true;
39
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
+ }
40
95
 
41
- // projects/hakistack/i18n/cli/config.ts
42
- var CONFIG_BASENAMES = [
43
- "i18n.config.ts",
44
- "i18n.config.mts",
45
- "i18n.config.cts",
46
- "i18n.config.js",
47
- "i18n.config.mjs",
48
- "i18n.config.cjs",
49
- "i18n.config.json"
50
- ];
51
- var DEFAULTS = {
52
- srcRoot: "src",
53
- definitionsDir: "src/i18n/definitions",
54
- outputDir: "src/assets/i18n",
55
- locales: ["en"],
56
- packageName: "@hakistack/i18n",
57
- directiveSelector: "appTranslate",
58
- directiveClassName: "AppTranslateDirective"
59
- };
60
- function findConfigFile(cwd) {
61
- for (const basename2 of CONFIG_BASENAMES) {
62
- const candidate = path.join(cwd, basename2);
63
- if (fs.existsSync(candidate)) return candidate;
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;
64
101
  }
65
- return null;
102
+ return byLang[lang] ?? byLang[defaultLang] ?? value.en;
66
103
  }
67
- async function loadConfig(cwd, overrides = {}) {
68
- let fileConfig = {};
69
- const configPath = findConfigFile(cwd);
70
- if (configPath) {
71
- if (configPath.endsWith(".json")) {
72
- fileConfig = JSON.parse(fs.readFileSync(configPath, "utf-8"));
73
- } else {
74
- const jiti = (0, import_jiti.createJiti)(__filename);
75
- const mod = await jiti.import(configPath);
76
- fileConfig = mod.default ?? mod;
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);
77
115
  }
78
116
  }
79
- const legacySourceLang = fileConfig.sourceLang;
80
- if (legacySourceLang !== void 0 && legacySourceLang !== SOURCE_LANG) {
81
- throw new Error(
82
- `i18n: 'sourceLang' is not configurable \u2014 the source locale is always '${SOURCE_LANG}' (t()'s first argument). Remove 'sourceLang' from ${configPath ?? "the config"}.`
83
- );
84
- }
85
- const merged = { ...DEFAULTS, ...stripUndefined(fileConfig), ...stripUndefined(overrides) };
86
- const requested = merged.locales && merged.locales.length > 0 ? merged.locales : DEFAULTS.locales;
87
- const locales = requested.includes(SOURCE_LANG) ? requested : [SOURCE_LANG, ...requested];
88
- return {
89
- cwd,
90
- srcRoot: path.resolve(cwd, merged.srcRoot),
91
- definitionsDir: path.resolve(cwd, merged.definitionsDir),
92
- outputDir: path.resolve(cwd, merged.outputDir),
93
- locales,
94
- sourceLang: SOURCE_LANG,
95
- packageName: merged.packageName,
96
- directiveSelector: merged.directiveSelector,
97
- directiveClassName: merged.directiveClassName
98
- };
117
+ return result;
99
118
  }
100
- function stripUndefined(obj) {
101
- const out = {};
102
- for (const [k, v] of Object.entries(obj)) {
103
- if (v !== void 0) out[k] = v;
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));
104
126
  }
105
- return out;
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, ".");
106
142
  }
107
-
108
- // projects/hakistack/i18n/cli/find-unused.ts
109
- var fs3 = __toESM(require("fs"));
110
- var path3 = __toESM(require("path"));
111
143
 
112
144
  // projects/hakistack/i18n/cli/load-registry.ts
113
- var fs2 = __toESM(require("fs"));
114
- var path2 = __toESM(require("path"));
115
- var import_jiti2 = require("jiti");
145
+ var fs = __toESM(require("fs"));
146
+ var path = __toESM(require("path"));
147
+ var import_jiti = require("jiti");
116
148
  function barrelPath(config) {
117
- return path2.join(config.definitionsDir, "index.generated.ts");
149
+ return path.join(config.definitionsDir, "index.generated.ts");
118
150
  }
119
151
  function keysPath(config) {
120
- return path2.join(config.definitionsDir, "keys.generated.ts");
152
+ return path.join(config.definitionsDir, "keys.generated.ts");
121
153
  }
154
+ var importFresh = (file) => (0, import_jiti.createJiti)(__filename, { moduleCache: false }).import(file);
122
155
  function ensureExists(file, hint) {
123
- if (!fs2.existsSync(file)) {
156
+ if (!fs.existsSync(file)) {
124
157
  throw new Error(`i18n: expected generated file not found:
125
158
  ${file}
126
159
  ${hint}`);
@@ -129,8 +162,7 @@ ${hint}`);
129
162
  async function loadRegistry(config) {
130
163
  const file = barrelPath(config);
131
164
  ensureExists(file, "Run the `scan` command first (`hakistack-i18n scan`).");
132
- const jiti = (0, import_jiti2.createJiti)(__filename);
133
- const mod = await jiti.import(file);
165
+ const mod = await importFresh(file);
134
166
  if (!mod.ALL_TRANSLATIONS) {
135
167
  throw new Error(`i18n: '${file}' does not export ALL_TRANSLATIONS. Re-run the scan.`);
136
168
  }
@@ -139,227 +171,260 @@ async function loadRegistry(config) {
139
171
  async function loadKeys(config) {
140
172
  const file = keysPath(config);
141
173
  ensureExists(file, "Run the `scan` command first (`hakistack-i18n scan`).");
142
- const jiti = (0, import_jiti2.createJiti)(__filename);
143
- const mod = await jiti.import(file);
174
+ const mod = await importFresh(file);
144
175
  if (!mod.TK) {
145
176
  throw new Error(`i18n: '${file}' does not export TK. Re-run the scan.`);
146
177
  }
147
178
  return mod.TK;
148
179
  }
149
180
 
150
- // projects/hakistack/i18n/cli/find-unused.ts
151
- var EXCLUDED_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "out-tsc", ".angular", ".cache"]);
152
- var TEST_FILE_RE = /\.spec\.ts$/;
153
- var I18N_FILE_RE = /\.i18n\.ts$/;
154
- var GENERATED_RE = /\.generated\.ts$/;
155
- var SCANNABLE_RE = /\.(ts|html)$/;
156
- var LITERAL_RE = /['"`]([a-z][a-zA-Z0-9_.]*?)['"`]/g;
157
- var ACCESSOR_RE = /\bTK(?:\.[a-zA-Z][a-zA-Z0-9_]*)+\b/g;
158
- var MARKER_RE = /\/\*\s*i18n-used:\s*([^*]+?)\s*\*\//g;
159
- function escapeRegex(s) {
160
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
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);
161
189
  }
162
- function contextVarRegex(directiveSelector) {
163
- return new RegExp(`\\*?${escapeRegex(directiveSelector)}\\s*=\\s*["'][^"']*?let\\s+([a-zA-Z_$][\\w$]*)`, "g");
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;
164
194
  }
165
- function contextVars(content, re) {
166
- const vars = /* @__PURE__ */ new Set();
167
- for (const m of content.matchAll(re)) vars.add(m[1]);
168
- return [...vars];
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
+ }
169
200
  }
170
- function walkLeafStrings(node, out) {
171
- if (typeof node === "string") {
172
- out.add(node);
173
- return;
201
+ function readManifest(file) {
202
+ try {
203
+ return JSON.parse(fs2.readFileSync(file, "utf-8"));
204
+ } catch {
205
+ return {};
174
206
  }
175
- if (node && typeof node === "object") for (const v of Object.values(node)) walkLeafStrings(v, out);
176
207
  }
177
- function walkTKAccessors(node, accessor, out) {
178
- if (typeof node === "string") {
179
- out.set(accessor.join("."), node);
180
- return;
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);
181
221
  }
182
- if (node && typeof node === "object") for (const [k, v] of Object.entries(node)) walkTKAccessors(v, [...accessor, k], out);
222
+ manifest[producer] = [...current].sort();
223
+ writeIfChanged(mPath, JSON.stringify(manifest, null, 2) + "\n");
224
+ return result;
183
225
  }
184
- function* walkSourceFiles(dir) {
185
- if (!fs3.existsSync(dir)) return;
186
- for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
187
- if (entry.name.startsWith(".") || EXCLUDED_DIRS.has(entry.name)) continue;
188
- const full = path3.join(dir, entry.name);
189
- if (entry.isDirectory()) yield* walkSourceFiles(full);
190
- else if (entry.isFile() && SCANNABLE_RE.test(entry.name)) yield full;
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);
191
230
  }
192
231
  }
193
- function lineOf(content, charIndex) {
194
- let line = 1;
195
- for (let i = 0; i < charIndex; i++) if (content.charCodeAt(i) === 10) line++;
196
- return line;
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');
197
251
  }
198
- function patternToRegex(claimed) {
199
- const escaped = claimed.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
200
- return new RegExp("^" + escaped + "$");
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;
201
262
  }
202
- async function runFindUnused(config, opts = {}) {
203
- const registry = await loadRegistry(config);
204
- const tk = await loadKeys(config);
205
- const allKeys = /* @__PURE__ */ new Set();
206
- for (const mod of registry) walkLeafStrings(mod.keys, allKeys);
207
- const accessorMap = /* @__PURE__ */ new Map();
208
- walkTKAccessors(tk, ["TK"], accessorMap);
209
- const keyToAccessors = /* @__PURE__ */ new Map();
210
- for (const [acc, key] of accessorMap) {
211
- const list = keyToAccessors.get(key) ?? [];
212
- list.push(acc);
213
- keyToAccessors.set(key, list);
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 });
214
275
  }
215
- const status = /* @__PURE__ */ new Map();
216
- for (const key of allKeys) {
217
- status.set(key, { key, accessors: keyToAccessors.get(key) ?? [], prodRefs: [], testRefs: [], claimedByMarker: false });
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
+ }
218
302
  }
219
- const contextVarRe = contextVarRegex(config.directiveSelector);
220
- for (const file of walkSourceFiles(config.srcRoot)) {
221
- if (I18N_FILE_RE.test(file) || GENERATED_RE.test(file)) continue;
222
- const isTest = TEST_FILE_RE.test(file);
223
- const relFile = path3.relative(config.cwd, file);
224
- const content = fs3.readFileSync(file, "utf-8");
225
- for (const m of content.matchAll(MARKER_RE)) {
226
- const pattern = patternToRegex(m[1].trim());
227
- for (const [key, st] of status) if (pattern.test(key)) st.claimedByMarker = true;
228
- }
229
- for (const m of content.matchAll(LITERAL_RE)) {
230
- const st = status.get(m[1]);
231
- if (!st) continue;
232
- (isTest ? st.testRefs : st.prodRefs).push({ file: relFile, line: lineOf(content, m.index ?? 0) });
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;
233
312
  }
234
- for (const m of content.matchAll(ACCESSOR_RE)) {
235
- const key = accessorMap.get(m[0]);
236
- if (!key) continue;
237
- const st = status.get(key);
238
- if (!st) continue;
239
- (isTest ? st.testRefs : st.prodRefs).push({ file: relFile, line: lineOf(content, m.index ?? 0) });
240
- }
241
- for (const varName of contextVars(content, contextVarRe)) {
242
- const re = new RegExp(`\\b${escapeRegex(varName)}((?:\\.[a-zA-Z_$][\\w$]*)+)`, "g");
243
- for (const m of content.matchAll(re)) {
244
- const st = status.get(m[1].slice(1));
245
- if (!st) continue;
246
- (isTest ? st.testRefs : st.prodRefs).push({ file: relFile, line: lineOf(content, m.index ?? 0) });
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]);
247
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
+ );
248
335
  }
249
336
  }
250
- const unused = [];
251
- const testOnly = [];
252
- const claimed = [];
253
- const used = [];
254
- for (const st of status.values()) {
255
- if (st.claimedByMarker) claimed.push(st);
256
- else if (st.prodRefs.length) used.push(st);
257
- else if (st.testRefs.length) testOnly.push(st);
258
- else unused.push(st);
259
- }
260
- for (const bucket of [unused, testOnly]) bucket.sort((a, b) => a.key.localeCompare(b.key));
261
- console.log("\n\u{1F50D} i18n unused-key detector\n" + "=".repeat(50));
262
- if (!unused.length && !testOnly.length) {
263
- console.log(`
264
- \u2713 All ${allKeys.size} keys are referenced.`);
265
- if (claimed.length) console.log(` (${claimed.length} claimed via /* i18n-used */ markers)`);
266
- console.log("");
267
- return;
268
- }
269
- if (unused.length) {
270
- console.log(`
271
- \u274C Unused (${unused.length}):
272
- `);
273
- for (const st of unused) console.log(` ${st.key}`);
274
- }
275
- if (testOnly.length) {
276
- console.log(`
277
- \u26A0\uFE0F Test-only (${testOnly.length}) \u2014 referenced ONLY in *.spec.ts:
278
- `);
279
- for (const st of testOnly) {
280
- console.log(` ${st.key}`);
281
- if (opts.verbose) for (const ref of st.testRefs.slice(0, 3)) console.log(` ${ref.file}:${ref.line}`);
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 }).`);
282
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 });
283
356
  }
284
- console.log(
285
- `
286
- \u{1F4CA} Summary
287
- Total: ${allKeys.size} Used: ${used.length} Test-only: ${testOnly.length} Claimed: ${claimed.length} Unused: ${unused.length}
288
- `
289
- );
290
- if (opts.strict && unused.length) {
291
- console.log("\u274C --strict: failing because unused keys were found.\n");
292
- process.exitCode = 1;
293
- }
294
- }
295
-
296
- // projects/hakistack/i18n/cli/generate.ts
297
- var fs4 = __toESM(require("fs"));
298
- var path4 = __toESM(require("path"));
299
-
300
- // projects/hakistack/i18n/engine/build-tree.ts
301
- function getTranslation(value, lang, defaultLang) {
302
- const byLang = value;
303
- if (lang === defaultLang) {
304
- return byLang[defaultLang] ?? value.en;
305
- }
306
- return byLang[lang] ?? byLang[defaultLang] ?? value.en;
357
+ return found;
307
358
  }
308
- function extractLanguage(translations, lang, defaultLang) {
309
- const result = {};
310
- for (const [key, value] of Object.entries(translations)) {
311
- if (isTranslationValue(value)) {
312
- result[key] = getTranslation(value, lang, defaultLang);
313
- if (value.__comment) {
314
- result[`${key}.comment`] = value.__comment;
315
- }
316
- } else if (typeof value === "object" && value !== null) {
317
- result[key] = extractLanguage(value, lang, defaultLang);
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;
318
385
  }
319
386
  }
320
- return result;
387
+ return complete;
321
388
  }
322
- function setAtScope(target, scope, subtree) {
323
- const parts = scope.split(".");
324
- let current = target;
325
- for (let i = 0; i < parts.length - 1; i++) {
326
- const part = parts[i];
327
- const slot = current[part];
328
- if (slot === void 0 || typeof slot === "string") {
329
- current[part] = {};
330
- }
331
- current = current[part];
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;
332
396
  }
333
- const leaf = parts[parts.length - 1];
334
- const existing = current[leaf];
335
- if (existing && typeof existing === "object") {
336
- Object.assign(existing, subtree);
337
- } else {
338
- current[leaf] = subtree;
397
+ if (ts.isComputedPropertyName(name) && (ts.isStringLiteral(name.expression) || ts.isNoSubstitutionTemplateLiteral(name.expression))) {
398
+ return name.expression.text;
339
399
  }
400
+ return null;
340
401
  }
341
- function buildLanguageTree(registry, lang, defaultLang) {
342
- const tree = {};
343
- for (const mod of registry) {
344
- const subtree = extractLanguage(mod.translations, lang, defaultLang);
345
- setAtScope(tree, mod.scope, subtree);
346
- }
347
- return tree;
402
+ function formatLocation(loc, cwd) {
403
+ return `${path3.relative(cwd, loc.file).split(path3.sep).join("/")}:${loc.line}`;
348
404
  }
349
- function buildScopedTree(registry, lang, defaultLang, scope) {
350
- const wanted = normalizeScope(scope);
351
- for (const mod of registry) {
352
- if (mod.scoped && normalizeScope(mod.scope) === wanted) {
353
- return extractLanguage(mod.translations, lang, defaultLang);
354
- }
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 }]);
355
409
  }
356
- return null;
410
+ return index;
357
411
  }
358
- function scopeToFilesystemPath(scope) {
359
- return scope.replace(/\./g, "/");
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;
360
420
  }
361
- function normalizeScope(scope) {
362
- return scope.replace(/\//g, ".");
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
+ }
363
428
  }
364
429
 
365
430
  // projects/hakistack/i18n/cli/generate.ts
@@ -385,10 +450,21 @@ function analyze(translations, lang, defaultLang, prefix = "") {
385
450
  }
386
451
  return { total, translated, missing };
387
452
  }
388
- async function runGenerate(config) {
389
- console.log("\n\u{1F310} i18n JSON generation\n" + "=".repeat(50));
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));
390
456
  const registry = await loadRegistry(config);
391
- fs4.mkdirSync(config.outputDir, { recursive: true });
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
+ }
392
468
  let totalKeys = 0;
393
469
  const translatedByLang = {};
394
470
  const missingByLang = {};
@@ -402,87 +478,106 @@ async function runGenerate(config) {
402
478
  missingByLang[lang].push(...a.missing);
403
479
  }
404
480
  }
405
- const scopedModules = registry.filter((m) => m.scoped);
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";
406
484
  for (const lang of config.locales) {
407
- const rootTree = buildLanguageTree(registry, lang, SOURCE_LANG);
408
- const rootPath = path4.join(config.outputDir, `${lang}.json`);
409
- fs4.writeFileSync(rootPath, JSON.stringify(rootTree, null, 2) + "\n");
410
- console.log(`\u2713 ${path4.relative(config.cwd, rootPath)}`);
411
- for (const mod of scopedModules) {
412
- const scopedTree = buildScopedTree(registry, lang, SOURCE_LANG, mod.scope);
413
- if (!scopedTree) continue;
414
- const scopeDir = path4.join(config.outputDir, scopeToFilesystemPath(mod.scope));
415
- fs4.mkdirSync(scopeDir, { recursive: true });
416
- const scopePath = path4.join(scopeDir, `${lang}.json`);
417
- fs4.writeFileSync(scopePath, JSON.stringify(scopedTree, null, 2) + "\n");
418
- console.log(`\u2713 ${path4.relative(config.cwd, scopePath)}`);
419
- }
420
- }
421
- console.log(`
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(`
422
503
  \u{1F4CA} Coverage
423
504
  Total keys: ${totalKeys}`);
424
505
  for (const lang of config.locales) {
425
506
  const translated = translatedByLang[lang];
426
507
  const pct = totalKeys > 0 ? Math.round(translated / totalKeys * 100) : 100;
427
- console.log(`${pct === 100 ? "\u2713" : "\u26A0"} ${lang.toUpperCase()}: ${translated}/${totalKeys} (${pct}%)`);
508
+ info(`${pct === 100 ? "\u2713" : "\u26A0"} ${lang.toUpperCase()}: ${translated}/${totalKeys} (${pct}%)`);
428
509
  const missing = missingByLang[lang];
429
510
  if (missing.length && lang !== SOURCE_LANG) {
430
- console.log(
431
- ` Missing ${missing.length}: ${missing.slice(0, 3).join(", ")}${missing.length > 3 ? `, \u2026 +${missing.length - 3}` : ""}`
432
- );
511
+ info(` Missing ${missing.length}: ${missing.slice(0, 3).join(", ")}${missing.length > 3 ? `, \u2026 +${missing.length - 3}` : ""}`);
433
512
  }
434
513
  }
435
- console.log("\n\u2713 Generation complete.\n");
436
- }
437
-
438
- // projects/hakistack/i18n/cli/scan.ts
439
- var fs5 = __toESM(require("fs"));
440
- var path5 = __toESM(require("path"));
441
- var SUFFIX = ".i18n.ts";
442
- function collectI18nFiles(dir, out = []) {
443
- if (!fs5.existsSync(dir)) return out;
444
- for (const entry of fs5.readdirSync(dir, { withFileTypes: true })) {
445
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
446
- const full = path5.join(dir, entry.name);
447
- if (entry.isDirectory()) {
448
- collectI18nFiles(full, out);
449
- } else if (entry.isFile() && entry.name.endsWith(SUFFIX)) {
450
- out.push(full);
451
- }
452
- }
453
- return out;
514
+ info("\n\u2713 Generation complete.\n");
515
+ return true;
454
516
  }
455
- function extractExports(sourceFile) {
456
- const content = fs5.readFileSync(sourceFile, "utf-8");
457
- const pattern = /export\s+const\s+([A-Z][A-Z0-9_]*)\s*=\s*defineTranslations\s*(?:<[^>]*>)?\s*\(\s*(['"])([^'"]+)\2/g;
458
- const looser = /export\s+const\s+([A-Z][A-Z0-9_]*)\s*=\s*defineTranslations\s*[<(]/g;
459
- const withScope = /* @__PURE__ */ new Map();
460
- for (const m of content.matchAll(pattern)) {
461
- withScope.set(m[1], m[3]);
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)},`);
462
537
  }
463
- const all = [];
464
- for (const m of content.matchAll(looser)) {
465
- const name = m[1];
466
- all.push({ name, scope: withScope.get(name) ?? null });
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(" },");
467
550
  }
468
- return all;
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;
469
569
  }
470
- function toImportPath(sourceFile, definitionsDir) {
471
- const relative5 = path5.relative(definitionsDir, sourceFile).replace(/\.ts$/, "");
472
- const posix = relative5.split(path5.sep).join("/");
473
- return posix.startsWith(".") ? posix : "./" + posix;
570
+ function dataModule(file, tree) {
571
+ return `${HEADER(file)}export default ${JSON.stringify(tree, null, 2)};
572
+ `;
474
573
  }
475
- function discover(config) {
476
- const files = collectI18nFiles(config.srcRoot);
477
- const modules = [];
478
- for (const file of files) {
479
- const importPath = toImportPath(file, config.definitionsDir);
480
- for (const { name, scope } of extractExports(file)) {
481
- modules.push({ exportName: name, scope, importPath, sourceFile: file });
482
- }
483
- }
484
- modules.sort((a, b) => a.exportName.localeCompare(b.exportName));
485
- return modules;
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);
486
581
  }
487
582
  function emitBarrel(modules) {
488
583
  const byPath = /* @__PURE__ */ new Map();
@@ -496,6 +591,7 @@ function emitBarrel(modules) {
496
591
  const tupleEntries = modules.map((m) => ` ${m.exportName}`).join(",\n");
497
592
  return [
498
593
  GENERATED_HEADER("index.generated.ts"),
594
+ LOCALES_REFERENCE,
499
595
  "",
500
596
  ...importLines,
501
597
  "",
@@ -512,56 +608,78 @@ function emitBarrel(modules) {
512
608
  ].join("\n");
513
609
  }
514
610
  function newNode() {
515
- return { refs: [], children: /* @__PURE__ */ new Map() };
611
+ return { leaf: null, params: [], refs: [], children: /* @__PURE__ */ new Map() };
516
612
  }
517
613
  function buildTKTree(modules) {
518
614
  const root = newNode();
519
- const usable = [];
615
+ const refs = [];
520
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);
521
621
  for (const mod of modules) {
522
622
  if (!mod.scope) continue;
523
- usable.push(mod);
524
623
  (byScope.get(mod.scope) ?? byScope.set(mod.scope, []).get(mod.scope)).push(mod.exportName);
525
- const parts = mod.scope.split(".");
526
- let node = root;
527
- for (const part of parts) {
528
- if (!node.children.has(part)) node.children.set(part, newNode());
529
- node = node.children.get(part);
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 });
530
631
  }
531
- node.refs.push(mod.exportName);
532
632
  }
533
633
  const duplicateScopes = new Map([...byScope].filter(([, names]) => names.length > 1));
534
- return { tree: root, usable, duplicateScopes };
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);
535
639
  }
536
- function serializeTKNode(node, indent) {
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
+ }
537
649
  const childIndent = indent + " ";
538
650
  const childEntries = [...node.children.entries()].sort(([a], [b]) => a.localeCompare(b));
539
- if (node.refs.length === 1 && childEntries.length === 0) {
540
- return `${node.refs[0]}.keys`;
541
- }
542
- const lines = ["{"];
543
- for (const ref of node.refs) {
544
- lines.push(`${childIndent}...${ref}.keys,`);
545
- }
546
- for (const [key, child] of childEntries) {
547
- lines.push(`${childIndent}${key}: ${serializeTKNode(child, childIndent)},`);
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") : "{}");
548
659
  }
549
- lines.push(`${indent}}`);
550
- return lines.join("\n");
660
+ if (parts.length === 1) return parts[0];
661
+ usage.mergeKeys = true;
662
+ return `mergeKeys(${parts.join(", ")})`;
551
663
  }
552
- function emitKeys(modules) {
553
- const { tree, usable } = buildTKTree(modules);
554
- const importNames = [...new Set(usable.map((m) => m.exportName))].sort();
555
- const importLine = importNames.length ? `import { ${importNames.join(", ")} } from './index.generated';` : "";
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 };
556
668
  const topEntries = [...tree.children.entries()].sort(([a], [b]) => a.localeCompare(b));
557
- const body = topEntries.map(([key, child]) => ` ${key}: ${serializeTKNode(child, " ")},`).join("\n");
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);
558
675
  return [
559
676
  GENERATED_HEADER("keys.generated.ts"),
677
+ LOCALES_REFERENCE,
560
678
  "",
561
- importLine,
679
+ ...imports,
562
680
  "",
563
681
  "/**",
564
- " * Unified translation keys (TK) \u2014 flat camelCase, one mental model.",
682
+ " * Unified translation keys (TK) \u2014 one mental model.",
565
683
  " * `TK.home.welcome` equals the literal key string `'home.welcome'`.",
566
684
  " *",
567
685
  " * Use in components with `translateSignal(TK.home.welcome)` and in templates",
@@ -576,6 +694,22 @@ function emitKeys(modules) {
576
694
  ""
577
695
  ].join("\n");
578
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
+ }
579
713
  function emitDirective(config) {
580
714
  const sel = config.directiveSelector;
581
715
  return [
@@ -620,67 +754,86 @@ function GENERATED_HEADER(file) {
620
754
  " */"
621
755
  ].join("\n");
622
756
  }
623
- function writeIfChanged(file, content) {
624
- if (fs5.existsSync(file) && fs5.readFileSync(file, "utf-8") === content) return false;
625
- fs5.mkdirSync(path5.dirname(file), { recursive: true });
626
- fs5.writeFileSync(file, content, "utf-8");
627
- return true;
628
- }
629
757
  function runScan(config, opts = {}) {
630
- const modules = discover(config);
758
+ const { modules, issues } = discover(config);
631
759
  const log = opts.quiet ? () => {
632
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);
633
771
  if (modules.length === 0) {
634
772
  console.error(`\u274C No translation modules found under ${config.srcRoot} (expected at least one *.i18n.ts).`);
635
773
  if (!opts.listOnly) process.exitCode = 1;
636
- return { moduleCount: 0, changed: [], missingScopes: [] };
774
+ return { ok: !!opts.listOnly, moduleCount: 0, changed: [], missingScopes: [] };
637
775
  }
638
776
  log(`
639
777
  \u{1F50D} i18n scan \u2014 discovered ${modules.length} module${modules.length === 1 ? "" : "s"}:`);
640
778
  for (const mod of modules) {
641
- log(` \u2022 ${mod.exportName}${mod.scope ? ` (${mod.scope})` : ""} \u2190 ${mod.importPath}`);
779
+ log(` \u2022 ${mod.exportName}${mod.scope ? ` (${mod.scope})` : ""} \u2190 ${at({ file: mod.sourceFile, line: mod.line })}`);
642
780
  }
643
- const missingScopes = modules.filter((m) => !m.scope).map((m) => m.exportName);
644
- if (missingScopes.length) {
645
- console.warn(
646
- `
647
- \u26A0\uFE0F Could not statically read the scope for: ${missingScopes.join(", ")}.
648
- These are excluded from the TK literal. Use a string-literal scope:
649
- export const X = defineTranslations('scope', { \u2026 }).`
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)))
650
794
  );
651
795
  }
796
+ const missingScopes = modules.filter((m) => !m.scope).map((m) => m.exportName);
652
797
  const { duplicateScopes } = buildTKTree(modules);
653
798
  for (const [scope, names] of duplicateScopes) {
654
- console.warn(`
655
- \u26A0\uFE0F Scope '${scope}' is defined by ${names.join(" and ")}; their keys are merged into TK.${scope}.`);
799
+ log(`
800
+ \u2139\uFE0E Scope '${scope}' is shared by ${names.join(", ")}; their keys are merged into TK${tkPath(scope)}.`);
656
801
  }
657
802
  if (opts.listOnly) {
658
803
  log("\n\u2713 Listing only (--list); no files emitted.\n");
659
- return { moduleCount: modules.length, changed: [], missingScopes };
804
+ return { ok: true, moduleCount: modules.length, changed: [], missingScopes };
660
805
  }
661
- const outputs = [
806
+ const result = syncOutputs(config.cwd, `scan:${config.definitionsDir}`, config.definitionsDir, [
662
807
  { file: path5.join(config.definitionsDir, "index.generated.ts"), content: emitBarrel(modules) },
663
- { file: path5.join(config.definitionsDir, "keys.generated.ts"), content: emitKeys(modules) },
664
- { file: path5.join(config.definitionsDir, `${config.directiveSelector}.directive.ts`), content: emitDirective(config) }
665
- ];
666
- const changed = [];
667
- for (const { file, content } of outputs) {
668
- if (writeIfChanged(file, content)) changed.push(path5.relative(config.cwd, file));
669
- }
670
- if (changed.length) {
671
- log(`
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(`
672
815
  \u2713 Wrote:
673
- ${changed.map((f) => ` ${f}`).join("\n")}
674
- `);
675
- } else {
676
- log("\n\u2713 Up to date \u2014 no changes.\n");
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);
677
828
  }
678
- return { moduleCount: modules.length, changed, missingScopes };
829
+ }
830
+ function tkPath(scope) {
831
+ return scope.split(".").map((part) => IDENTIFIER_RE.test(part) ? `.${part}` : `['${part}']`).join("");
679
832
  }
680
833
 
681
834
  // projects/hakistack/i18n/cli/validate.ts
682
835
  function extractPlaceholders(text) {
683
- return (text.match(/\{\{[^}]+}}/g) || []).sort();
836
+ return (text.match(/\{\{[^}]+}}/g) || []).map((p) => `{{${p.slice(2, -2).trim()}}}`).sort();
684
837
  }
685
838
  function arraysEqual(a, b) {
686
839
  return a.length === b.length && a.every((v, i) => v === b[i]);
@@ -742,9 +895,21 @@ function validateNode(obj, moduleName, locales, defaultLang, errors, stubs, keyP
742
895
  }
743
896
  }
744
897
  }
745
- async function runValidate(config) {
746
- console.log("\n\u{1F50D} i18n validation\n" + "=".repeat(50));
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));
747
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
+ }
748
913
  const errors = [];
749
914
  const stubs = [];
750
915
  for (const mod of registry) {
@@ -753,57 +918,348 @@ async function runValidate(config) {
753
918
  const actualErrors = errors.filter((e) => e.severity === "error");
754
919
  const warnings = errors.filter((e) => e.severity === "warning");
755
920
  if (actualErrors.length === 0 && warnings.length === 0 && stubs.length === 0) {
756
- console.log("\n\u2713 All translations are valid!\n");
757
- return;
921
+ info("\n\u2713 All translations are valid!\n");
922
+ return true;
758
923
  }
759
924
  if (actualErrors.length) {
760
925
  console.log(`
761
926
  \u274C ${actualErrors.length} error(s):
762
927
  `);
763
928
  for (const e of actualErrors) {
929
+ const where = locate(`${e.module}.${e.key}`)[0];
764
930
  console.log(` [${e.module}] ${e.key} (${e.language.toUpperCase()})
765
- \u2192 ${e.issue}`);
931
+ \u2192 ${e.issue}${where ? `
932
+ at ${where}` : ""}`);
766
933
  }
767
934
  }
768
935
  if (warnings.length) {
769
- console.log(`
936
+ info(`
770
937
  \u26A0\uFE0F ${warnings.length} warning(s):
771
938
  `);
772
939
  const byLang = {};
773
940
  for (const w of warnings) (byLang[w.language] ??= []).push(w);
774
941
  for (const [lang, list] of Object.entries(byLang)) {
775
- console.log(` ${lang.toUpperCase()}: ${list.length} missing`);
776
- for (const w of list.slice(0, 5)) console.log(` - ${w.key}`);
777
- if (list.length > 5) console.log(` \u2026 and ${list.length - 5} more`);
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`);
778
945
  }
779
946
  }
780
947
  if (stubs.length) {
781
- console.log(`
948
+ info(`
782
949
  \u{1F4DD} Stub report \u2014 ${stubs.length} source-only ${stubs.length === 1 ? "leaf" : "leaves"}:
783
950
  `);
784
951
  const byModule = {};
785
952
  for (const s of stubs) (byModule[s.module] ??= []).push(s.key);
786
953
  for (const [moduleName, keys] of Object.entries(byModule)) {
787
- console.log(` ${moduleName}: ${keys.length}`);
788
- for (const k of keys.slice(0, 5)) console.log(` - ${k}`);
789
- if (keys.length > 5) console.log(` \u2026 and ${keys.length - 5} more`);
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`);
790
957
  }
791
958
  }
792
- console.log(`
959
+ info(`
793
960
  \u{1F4CA} Summary
794
961
  Errors: ${actualErrors.length} Warnings: ${warnings.length} Stubs: ${stubs.length}`);
795
962
  if (actualErrors.length) {
796
963
  console.log("\n\u274C Validation failed!\n");
797
964
  process.exitCode = 1;
798
- } else {
799
- console.log("\n\u2713 Validation passed.\n");
965
+ return false;
800
966
  }
967
+ info("\n\u2713 Validation passed.\n");
968
+ return true;
801
969
  }
802
970
 
803
- // projects/hakistack/i18n/cli/watch.ts
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"));
804
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"));
805
1262
  var import_jiti3 = require("jiti");
806
- var SUFFIX2 = ".i18n.ts";
807
1263
  async function runWatch(config) {
808
1264
  let chokidar;
809
1265
  try {
@@ -814,24 +1270,24 @@ async function runWatch(config) {
814
1270
  process.exitCode = 1;
815
1271
  return;
816
1272
  }
817
- runScan(config, { quiet: true });
818
- console.log(`[i18n-watch] watching ${path6.relative(config.cwd, config.srcRoot)}/**/*${SUFFIX2}`);
1273
+ await runCycle(config);
1274
+ console.log(`[i18n-watch] watching ${path8.relative(config.cwd, config.srcRoot)}/**/*${I18N_SUFFIX}`);
819
1275
  let running = false;
820
1276
  let pending = false;
821
- const trigger = (label) => {
1277
+ const trigger = async (label) => {
822
1278
  if (running) {
823
1279
  pending = true;
824
1280
  return;
825
1281
  }
826
1282
  running = true;
827
- console.log(`[i18n-watch] ${label} \u2014 scanning`);
1283
+ console.log(`[i18n-watch] ${label}`);
828
1284
  try {
829
- runScan(config, { quiet: true });
1285
+ await runCycle(config);
830
1286
  } finally {
831
1287
  running = false;
832
1288
  if (pending) {
833
1289
  pending = false;
834
- trigger("coalesced");
1290
+ void trigger("more changes");
835
1291
  }
836
1292
  }
837
1293
  };
@@ -839,17 +1295,27 @@ async function runWatch(config) {
839
1295
  ignoreInitial: true,
840
1296
  awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 30 },
841
1297
  ignored: (p, stats) => {
842
- const base = path6.basename(p);
1298
+ const base = path8.basename(p);
843
1299
  if (base === "node_modules" || base.startsWith(".")) return true;
844
- if (stats?.isFile()) return !p.endsWith(SUFFIX2);
1300
+ if (stats?.isFile()) return !p.endsWith(I18N_SUFFIX);
845
1301
  return false;
846
1302
  }
847
1303
  });
848
- watcher.on("add", (p) => trigger(`add ${path6.relative(config.cwd, p)}`)).on("unlink", (p) => trigger(`remove ${path6.relative(config.cwd, p)}`)).on("change", (p) => trigger(`change ${path6.relative(config.cwd, p)}`));
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)}`));
849
1305
  const shutdown = () => watcher.close().then(() => process.exit(0));
850
1306
  process.on("SIGINT", shutdown);
851
1307
  process.on("SIGTERM", shutdown);
852
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
+ }
853
1319
 
854
1320
  // projects/hakistack/i18n/cli/bin.ts
855
1321
  function parseArgs(argv) {
@@ -883,11 +1349,12 @@ var HELP = `hakistack-i18n \u2014 type-safe i18n codegen
883
1349
  Usage: hakistack-i18n <command> [flags]
884
1350
 
885
1351
  Commands:
1352
+ check scan + validate + generate \u2014 the everyday command (prebuild, CI)
886
1353
  scan Discover *.i18n.ts and emit barrel + TK literal + typed directive
887
1354
  generate Write JSON translation files
888
1355
  validate Gate on missing / placeholder-mismatched translations
889
1356
  find-unused Report defined keys with no references
890
- watch Re-run scan on *.i18n.ts changes
1357
+ watch Re-run scan + validate + generate on *.i18n.ts changes
891
1358
 
892
1359
  Flags:
893
1360
  --config <path> Explicit config file
@@ -898,6 +1365,7 @@ Flags:
898
1365
  --list (scan) list modules without emitting
899
1366
  --strict (find-unused) exit 1 if unused keys exist
900
1367
  --verbose (find-unused) print reference locations
1368
+ --quiet (check) print changes and errors only
901
1369
  `;
902
1370
  async function main() {
903
1371
  const { command, flags } = parseArgs(process.argv.slice(2));
@@ -908,10 +1376,13 @@ async function main() {
908
1376
  const cwd = process.cwd();
909
1377
  const overrides = configOverrides(flags);
910
1378
  if (typeof flags["config"] === "string") {
911
- process.chdir(path7.dirname(path7.resolve(cwd, flags["config"])));
1379
+ process.chdir(path9.dirname(path9.resolve(cwd, flags["config"])));
912
1380
  }
913
1381
  const config = await loadConfig(process.cwd(), overrides);
914
1382
  switch (command) {
1383
+ case "check":
1384
+ await runCheck(config, { quiet: flags["quiet"] === true });
1385
+ break;
915
1386
  case "scan":
916
1387
  runScan(config, { listOnly: flags["list"] === true });
917
1388
  break;