ai-localize-locale-engine 2.0.1 → 2.0.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # ai-localize-locale-engine
2
2
 
3
+ ## 2.0.3
4
+
5
+ ### Minor Changes
6
+
7
+ - **`staticKeys` injection** — `Extractor` and `Writer` now merge `staticKeys` entries from config into every generated locale file; in nested mode they are placed in the default namespace file; in flat mode they are merged at the top level
8
+ - **`keyStyle: "screaming_snake"` support** — `Extractor` honours the new `keyStyle` config field; when set to `"screaming_snake"` all scanned hardcoded text generates UPPER_SNAKE_CASE keys matching the text value
9
+
10
+ ### Patch Changes
11
+
12
+ - Updated dependencies
13
+ - ai-localize-shared@2.0.3
14
+ - ai-localize-config@2.0.3
15
+
16
+ ## 2.0.2
17
+
18
+ ### Minor Changes
19
+
20
+ - **Copy source value to target languages** — locale extract now initialises target language entries with the English source value instead of an empty string, so translators have immediate context
21
+ - **Flat locale file layout** — `localeStructure: "flat"` writes one `<lang>.json` per language with all namespace keys merged; non-default namespace keys are prefixed with `<namespace>.` to avoid collisions
22
+
23
+ ### Patch Changes
24
+
25
+ - Updated dependencies
26
+ - ai-localize-shared@2.0.2
27
+
3
28
  ## 2.0.1
4
29
 
5
30
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -4,6 +4,26 @@ interface ExtractOptions {
4
4
  defaultLanguage?: string;
5
5
  targetLanguages?: string[];
6
6
  namespaceSplitting?: boolean;
7
+ /**
8
+ * Static key/value pairs to inject into every generated locale file,
9
+ * in addition to the keys discovered by scanning source files.
10
+ *
11
+ * These keys are placed in the default namespace (`common` / `translation`)
12
+ * so they end up in `locales/<lang>/translation.json` (nested mode) or at
13
+ * the top level of `locales/<lang>.json` (flat mode).
14
+ *
15
+ * Static keys that collide with scanned keys are **skipped** — scanned
16
+ * keys always take precedence so existing translations are never overwritten.
17
+ *
18
+ * Example:
19
+ * staticKeys: {
20
+ * MAX_COUNT: "Max Count",
21
+ * ALLOWED: "Allowed",
22
+ * DISABLED: "Disabled",
23
+ * UNLIMITED: "Unlimited",
24
+ * }
25
+ */
26
+ staticKeys?: Record<string, string>;
7
27
  }
8
28
  interface ExtractionResult {
9
29
  localeFiles: LocaleFile[];
package/dist/index.d.ts CHANGED
@@ -4,6 +4,26 @@ interface ExtractOptions {
4
4
  defaultLanguage?: string;
5
5
  targetLanguages?: string[];
6
6
  namespaceSplitting?: boolean;
7
+ /**
8
+ * Static key/value pairs to inject into every generated locale file,
9
+ * in addition to the keys discovered by scanning source files.
10
+ *
11
+ * These keys are placed in the default namespace (`common` / `translation`)
12
+ * so they end up in `locales/<lang>/translation.json` (nested mode) or at
13
+ * the top level of `locales/<lang>.json` (flat mode).
14
+ *
15
+ * Static keys that collide with scanned keys are **skipped** — scanned
16
+ * keys always take precedence so existing translations are never overwritten.
17
+ *
18
+ * Example:
19
+ * staticKeys: {
20
+ * MAX_COUNT: "Max Count",
21
+ * ALLOWED: "Allowed",
22
+ * DISABLED: "Disabled",
23
+ * UNLIMITED: "Unlimited",
24
+ * }
25
+ */
26
+ staticKeys?: Record<string, string>;
7
27
  }
8
28
  interface ExtractionResult {
9
29
  localeFiles: LocaleFile[];
package/dist/index.js CHANGED
@@ -47,7 +47,8 @@ var LocaleExtractor = class {
47
47
  this.options = {
48
48
  defaultLanguage: options.defaultLanguage || "en",
49
49
  targetLanguages: options.targetLanguages || [],
50
- namespaceSplitting: options.namespaceSplitting ?? true
50
+ namespaceSplitting: options.namespaceSplitting ?? true,
51
+ staticKeys: options.staticKeys ?? {}
51
52
  };
52
53
  }
53
54
  extract(detectedTexts) {
@@ -67,6 +68,18 @@ var LocaleExtractor = class {
67
68
  if (!namespaceMap.has(namespace)) namespaceMap.set(namespace, {});
68
69
  namespaceMap.get(namespace)[localKey] = value;
69
70
  }
71
+ const staticKeys = this.options.staticKeys;
72
+ if (staticKeys && Object.keys(staticKeys).length > 0) {
73
+ if (!namespaceMap.has(import_ai_localize_shared.DEFAULT_NAMESPACE)) {
74
+ namespaceMap.set(import_ai_localize_shared.DEFAULT_NAMESPACE, {});
75
+ }
76
+ const defaultNsBucket = namespaceMap.get(import_ai_localize_shared.DEFAULT_NAMESPACE);
77
+ for (const [key, value] of Object.entries(staticKeys)) {
78
+ if (!(key in defaultNsBucket)) {
79
+ defaultNsBucket[key] = value;
80
+ }
81
+ }
82
+ }
70
83
  for (const [ns, entries] of namespaceMap) {
71
84
  namespaceMap.set(
72
85
  ns,
@@ -77,7 +90,8 @@ var LocaleExtractor = class {
77
90
  const allLanguages = [this.options.defaultLanguage, ...this.options.targetLanguages];
78
91
  for (const lang of allLanguages) {
79
92
  for (const [namespace, entries] of namespaceMap) {
80
- const langEntries = { ...entries };
93
+ const isDefault = lang === this.options.defaultLanguage;
94
+ const langEntries = isDefault ? { ...entries } : Object.fromEntries(Object.keys(entries).map((k) => [k, ""]));
81
95
  localeFiles.push({ language: lang, namespace, entries: langEntries, filePath: "" });
82
96
  }
83
97
  }
package/dist/index.mjs CHANGED
@@ -10,7 +10,8 @@ var LocaleExtractor = class {
10
10
  this.options = {
11
11
  defaultLanguage: options.defaultLanguage || "en",
12
12
  targetLanguages: options.targetLanguages || [],
13
- namespaceSplitting: options.namespaceSplitting ?? true
13
+ namespaceSplitting: options.namespaceSplitting ?? true,
14
+ staticKeys: options.staticKeys ?? {}
14
15
  };
15
16
  }
16
17
  extract(detectedTexts) {
@@ -30,6 +31,18 @@ var LocaleExtractor = class {
30
31
  if (!namespaceMap.has(namespace)) namespaceMap.set(namespace, {});
31
32
  namespaceMap.get(namespace)[localKey] = value;
32
33
  }
34
+ const staticKeys = this.options.staticKeys;
35
+ if (staticKeys && Object.keys(staticKeys).length > 0) {
36
+ if (!namespaceMap.has(DEFAULT_NAMESPACE)) {
37
+ namespaceMap.set(DEFAULT_NAMESPACE, {});
38
+ }
39
+ const defaultNsBucket = namespaceMap.get(DEFAULT_NAMESPACE);
40
+ for (const [key, value] of Object.entries(staticKeys)) {
41
+ if (!(key in defaultNsBucket)) {
42
+ defaultNsBucket[key] = value;
43
+ }
44
+ }
45
+ }
33
46
  for (const [ns, entries] of namespaceMap) {
34
47
  namespaceMap.set(
35
48
  ns,
@@ -40,7 +53,8 @@ var LocaleExtractor = class {
40
53
  const allLanguages = [this.options.defaultLanguage, ...this.options.targetLanguages];
41
54
  for (const lang of allLanguages) {
42
55
  for (const [namespace, entries] of namespaceMap) {
43
- const langEntries = { ...entries };
56
+ const isDefault = lang === this.options.defaultLanguage;
57
+ const langEntries = isDefault ? { ...entries } : Object.fromEntries(Object.keys(entries).map((k) => [k, ""]));
44
58
  localeFiles.push({ language: lang, namespace, entries: langEntries, filePath: "" });
45
59
  }
46
60
  }
package/package.json CHANGED
@@ -1,10 +1,15 @@
1
1
  {
2
2
  "name": "ai-localize-locale-engine",
3
- "version": "2.0.1",
3
+ "version": "2.0.4",
4
4
  "description": "Locale file generation, merging, deduplication and synchronization",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
7
7
  "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "README.md",
11
+ "CHANGELOG.md"
12
+ ],
8
13
  "exports": {
9
14
  ".": {
10
15
  "types": "./dist/index.d.ts",
@@ -12,8 +17,23 @@
12
17
  "require": "./dist/index.js"
13
18
  }
14
19
  },
20
+ "keywords": [
21
+ "i18n",
22
+ "localization",
23
+ "l10n",
24
+ "internationalization",
25
+ "ai-localize",
26
+ "locale",
27
+ "locale-files",
28
+ "json",
29
+ "translation",
30
+ "extraction"
31
+ ],
32
+ "engines": {
33
+ "node": ">=18.0.0"
34
+ },
15
35
  "dependencies": {
16
- "ai-localize-shared": "2.0.1"
36
+ "ai-localize-shared": "2.0.4"
17
37
  },
18
38
  "devDependencies": {
19
39
  "tsup": "^8.0.1",
@@ -1,52 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { LocaleExtractor } from '../extractor.js';
3
- import type { DetectedText } from 'ai-localize-shared';
4
-
5
- const mockTexts: DetectedText[] = [
6
- {
7
- filePath: 'src/pages/Home.tsx',
8
- line: 5,
9
- column: 0,
10
- text: 'Welcome to our app',
11
- suggestedKey: 'pages.home.welcome_to_our_app',
12
- context: 'jsx-text',
13
- nodeType: 'JSXText',
14
- alreadyTranslated: false,
15
- },
16
- {
17
- filePath: 'src/components/Button.tsx',
18
- line: 3,
19
- column: 0,
20
- text: 'Save',
21
- suggestedKey: 'components.button.save',
22
- context: 'jsx-text',
23
- nodeType: 'JSXText',
24
- alreadyTranslated: false,
25
- },
26
- ];
27
-
28
- describe('LocaleExtractor', () => {
29
- it('extracts locale keys into locale files', () => {
30
- const extractor = new LocaleExtractor({
31
- defaultLanguage: 'en',
32
- targetLanguages: ['fr'],
33
- namespaceSplitting: true,
34
- });
35
- const { localeFiles, keyCount } = extractor.extract(mockTexts);
36
- expect(keyCount).toBe(2);
37
- expect(localeFiles.length).toBeGreaterThan(0);
38
- });
39
-
40
- it('creates empty entries for target languages', () => {
41
- const extractor = new LocaleExtractor({
42
- defaultLanguage: 'en',
43
- targetLanguages: ['fr', 'de'],
44
- namespaceSplitting: false,
45
- });
46
- const { localeFiles } = extractor.extract(mockTexts);
47
- const frFiles = localeFiles.filter((f) => f.language === 'fr');
48
- expect(frFiles.length).toBeGreaterThan(0);
49
- const frEntries = Object.values(frFiles[0].entries);
50
- expect(frEntries.every((v) => v === '')).toBe(true);
51
- });
52
- });
@@ -1,19 +0,0 @@
1
- import type { DetectedText } from "ai-localize-shared";
2
-
3
- export function deduplicateTexts(texts: DetectedText[]): DetectedText[] {
4
- const seen = new Map<string, DetectedText>();
5
- for (const dt of texts) {
6
- const key = dt.text.toLowerCase().trim();
7
- if (!seen.has(key)) seen.set(key, dt);
8
- }
9
- return Array.from(seen.values());
10
- }
11
-
12
- export function filterAlreadyTranslated(texts: DetectedText[], existingKeys: Set<string>): DetectedText[] {
13
- return texts.filter((dt) => !existingKeys.has(dt.suggestedKey));
14
- }
15
-
16
- export function findUnusedKeys(localeKeys: string[], sourceKeys: string[]): string[] {
17
- const sourceSet = new Set(sourceKeys);
18
- return localeKeys.filter((k) => !sourceSet.has(k));
19
- }
package/src/extractor.ts DELETED
@@ -1,76 +0,0 @@
1
- import type { DetectedText, LocaleFile } from "ai-localize-shared";
2
- import {
3
- splitKeyNamespace,
4
- resolveKeyCollision,
5
- DEFAULT_NAMESPACE,
6
- } from "ai-localize-shared";
7
-
8
- export interface ExtractOptions {
9
- defaultLanguage?: string;
10
- targetLanguages?: string[];
11
- namespaceSplitting?: boolean;
12
- }
13
-
14
- export interface ExtractionResult {
15
- localeFiles: LocaleFile[];
16
- keyCount: number;
17
- namespaces: string[];
18
- }
19
-
20
- export class LocaleExtractor {
21
- private options: Required<ExtractOptions>;
22
-
23
- constructor(options: ExtractOptions = {}) {
24
- this.options = {
25
- defaultLanguage: options.defaultLanguage || "en",
26
- targetLanguages: options.targetLanguages || [],
27
- namespaceSplitting: options.namespaceSplitting ?? true,
28
- };
29
- }
30
-
31
- extract(detectedTexts: DetectedText[]): ExtractionResult {
32
- const keyValueMap = new Map<string, string>();
33
- const existingKeys = new Set<string>();
34
-
35
- for (const dt of detectedTexts) {
36
- let key = dt.suggestedKey;
37
- if (keyValueMap.has(key) && keyValueMap.get(key) !== dt.text) {
38
- key = resolveKeyCollision(key, existingKeys);
39
- }
40
- existingKeys.add(key);
41
- keyValueMap.set(key, dt.text);
42
- }
43
-
44
- const namespaceMap = new Map<string, Record<string, string>>();
45
- for (const [key, value] of keyValueMap) {
46
- const { namespace, localKey } = this.options.namespaceSplitting
47
- ? splitKeyNamespace(key)
48
- : { namespace: DEFAULT_NAMESPACE, localKey: key };
49
- if (!namespaceMap.has(namespace)) namespaceMap.set(namespace, {});
50
- namespaceMap.get(namespace)![localKey] = value;
51
- }
52
-
53
- for (const [ns, entries] of namespaceMap) {
54
- namespaceMap.set(
55
- ns,
56
- Object.fromEntries(Object.entries(entries).sort(([a], [b]) => a.localeCompare(b)))
57
- );
58
- }
59
-
60
- const localeFiles: LocaleFile[] = [];
61
- const allLanguages = [this.options.defaultLanguage, ...this.options.targetLanguages];
62
-
63
- for (const lang of allLanguages) {
64
- for (const [namespace, entries] of namespaceMap) {
65
- // All languages get the source (English) value as the initial translation.
66
- // This makes locale files immediately usable without blank values, and human
67
- // translators can identify untranslated strings by comparing them to the
68
- // default language file.
69
- const langEntries = { ...entries };
70
- localeFiles.push({ language: lang, namespace, entries: langEntries, filePath: "" });
71
- }
72
- }
73
-
74
- return { localeFiles, keyCount: keyValueMap.size, namespaces: Array.from(namespaceMap.keys()) };
75
- }
76
- }
package/src/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from "./extractor.js";
2
- export * from "./writer.js";
3
- export * from "./deduplicator.js";
4
- export * from "./synchronizer.js";
@@ -1,36 +0,0 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
- import { readJsonSafe, writeJson, ensureDir } from "ai-localize-shared";
4
-
5
- export class LocaleSynchronizer {
6
- constructor(private localesDir: string, private defaultLanguage = "en") {}
7
-
8
- sync(): { updated: string[]; addedKeys: number } {
9
- const updated: string[] = [];
10
- let addedKeys = 0;
11
- const defaultDir = path.join(this.localesDir, this.defaultLanguage);
12
- if (!fs.existsSync(defaultDir)) return { updated, addedKeys };
13
-
14
- const defaultFiles = fs.readdirSync(defaultDir).filter((f) => f.endsWith(".json"));
15
- const langDirs = fs
16
- .readdirSync(this.localesDir, { withFileTypes: true })
17
- .filter((e) => e.isDirectory() && e.name !== this.defaultLanguage)
18
- .map((e) => e.name);
19
-
20
- for (const namespace of defaultFiles) {
21
- const defaultEntries = readJsonSafe<Record<string, string>>(path.join(defaultDir, namespace));
22
- if (!defaultEntries) continue;
23
- for (const lang of langDirs) {
24
- const targetPath = path.join(this.localesDir, lang, namespace);
25
- ensureDir(path.dirname(targetPath));
26
- const existing = readJsonSafe<Record<string, string>>(targetPath) || {};
27
- let changed = false;
28
- for (const key of Object.keys(defaultEntries)) {
29
- if (!(key in existing)) { existing[key] = ""; addedKeys++; changed = true; }
30
- }
31
- if (changed) { writeJson(targetPath, existing); updated.push(targetPath); }
32
- }
33
- }
34
- return { updated, addedKeys };
35
- }
36
- }
package/src/writer.ts DELETED
@@ -1,164 +0,0 @@
1
- import * as path from "path";
2
- import type { LocaleFile } from "ai-localize-shared";
3
- import { writeJson, readJsonSafe, ensureDir } from "ai-localize-shared";
4
-
5
- export interface WriteOptions {
6
- localesDir: string;
7
- merge?: boolean;
8
- sort?: boolean;
9
- /**
10
- * Locale file layout.
11
- *
12
- * - `"nested"` (default) — one JSON file per language + namespace:
13
- * `locales/en/common.json`, `locales/en/dashboard.json`
14
- * For the "common" / default namespace the file is named `translation.json`.
15
- *
16
- * - `"flat"` — one JSON file per language, all namespaces merged:
17
- * `locales/en.json`, `locales/fr.json`
18
- * Namespace prefixes are prepended to keys to avoid collisions:
19
- * `common.button.save`, `dashboard.header.title`
20
- * (keys that already start with the namespace prefix are left as-is).
21
- */
22
- localeStructure?: "nested" | "flat";
23
- }
24
-
25
- export class LocaleWriter {
26
- private options: Required<WriteOptions>;
27
-
28
- constructor(options: WriteOptions) {
29
- this.options = {
30
- localesDir: options.localesDir,
31
- merge: options.merge ?? true,
32
- sort: options.sort ?? true,
33
- localeStructure: options.localeStructure ?? "nested",
34
- };
35
- }
36
-
37
- write(localeFiles: LocaleFile[]): { written: string[]; merged: string[]; created: string[] } {
38
- if (this.options.localeStructure === "flat") {
39
- return this.writeFlat(localeFiles);
40
- }
41
- return this.writeNested(localeFiles);
42
- }
43
-
44
- // ─── Nested layout ───────────────────────────────────────────────────────────
45
-
46
- private writeNested(localeFiles: LocaleFile[]): { written: string[]; merged: string[]; created: string[] } {
47
- const written: string[] = [];
48
- const merged: string[] = [];
49
- const created: string[] = [];
50
-
51
- for (const lf of localeFiles) {
52
- const filePath = this.resolveNestedFilePath(lf);
53
- lf.filePath = filePath;
54
- ensureDir(path.dirname(filePath));
55
- const existing = readJsonSafe<Record<string, string>>(filePath);
56
-
57
- if (existing && this.options.merge) {
58
- const mergedEntries = this.mergeEntries(existing, lf.entries);
59
- writeJson(filePath, this.options.sort ? this.sort(mergedEntries) : mergedEntries);
60
- merged.push(filePath);
61
- } else {
62
- writeJson(filePath, this.options.sort ? this.sort(lf.entries) : lf.entries);
63
- created.push(filePath);
64
- }
65
- written.push(filePath);
66
- }
67
-
68
- return { written, merged, created };
69
- }
70
-
71
- private resolveNestedFilePath(lf: LocaleFile): string {
72
- return lf.namespace === "common"
73
- ? path.join(this.options.localesDir, lf.language, "translation.json")
74
- : path.join(this.options.localesDir, lf.language, `${lf.namespace}.json`);
75
- }
76
-
77
- // ─── Flat layout ─────────────────────────────────────────────────────────────
78
-
79
- /**
80
- * In flat mode all LocaleFile entries for the same language are merged into
81
- * a single `<localesDir>/<language>.json` file.
82
- *
83
- * To avoid key collisions between namespaces, each key is prefixed with its
84
- * namespace name (e.g. `common.button.save`, `dashboard.header.title`).
85
- * Keys that already start with the namespace prefix are left unchanged.
86
- */
87
- private writeFlat(localeFiles: LocaleFile[]): { written: string[]; merged: string[]; created: string[] } {
88
- // Group locale files by language
89
- const byLanguage = new Map<string, LocaleFile[]>();
90
- for (const lf of localeFiles) {
91
- const list = byLanguage.get(lf.language) ?? [];
92
- list.push(lf);
93
- byLanguage.set(lf.language, list);
94
- }
95
-
96
- const written: string[] = [];
97
- const merged: string[] = [];
98
- const created: string[] = [];
99
-
100
- for (const [language, files] of byLanguage) {
101
- const filePath = path.join(this.options.localesDir, `${language}.json`);
102
- ensureDir(path.dirname(filePath));
103
-
104
- // Merge all namespace entries into a single flat object
105
- const incomingEntries: Record<string, string> = {};
106
- for (const lf of files) {
107
- for (const [key, value] of Object.entries(lf.entries)) {
108
- const flatKey = this.flattenKey(lf.namespace, key);
109
- incomingEntries[flatKey] = value;
110
- }
111
- }
112
-
113
- const existing = readJsonSafe<Record<string, string>>(filePath);
114
- if (existing && this.options.merge) {
115
- const mergedEntries = this.mergeEntries(existing, incomingEntries);
116
- writeJson(filePath, this.options.sort ? this.sort(mergedEntries) : mergedEntries);
117
- merged.push(filePath);
118
- } else {
119
- writeJson(filePath, this.options.sort ? this.sort(incomingEntries) : incomingEntries);
120
- created.push(filePath);
121
- }
122
-
123
- // Update filePath on each LocaleFile for reference
124
- for (const lf of files) {
125
- lf.filePath = filePath;
126
- }
127
-
128
- written.push(filePath);
129
- }
130
-
131
- return { written, merged, created };
132
- }
133
-
134
- /**
135
- * Produces a flat key with the namespace prepended.
136
- * If the key already starts with `<namespace>.` it is returned as-is
137
- * to avoid double-prefixing (e.g. when namespace splitting already embedded it).
138
- */
139
- private flattenKey(namespace: string, key: string): string {
140
- // "common" is the default namespace — don't prepend to avoid verbose keys
141
- if (namespace === "common" || namespace === "translation") {
142
- return key;
143
- }
144
- const prefix = `${namespace}.`;
145
- return key.startsWith(prefix) ? key : `${prefix}${key}`;
146
- }
147
-
148
- // ─── Helpers ─────────────────────────────────────────────────────────────────
149
-
150
- private mergeEntries(
151
- existing: Record<string, string>,
152
- incoming: Record<string, string>
153
- ): Record<string, string> {
154
- const result = { ...existing };
155
- for (const [key, value] of Object.entries(incoming)) {
156
- if (!(key in result) || result[key] === "") result[key] = value;
157
- }
158
- return result;
159
- }
160
-
161
- private sort(entries: Record<string, string>): Record<string, string> {
162
- return Object.fromEntries(Object.entries(entries).sort(([a], [b]) => a.localeCompare(b)));
163
- }
164
- }
package/tsconfig.json DELETED
@@ -1,6 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": { "outDir": "./dist", "rootDir": "./src" },
4
- "include": ["src/**/*"],
5
- "exclude": ["node_modules", "dist"]
6
- }