@zachhandley/ez-i18n 0.1.2 → 0.1.3
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/README.md +85 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +385 -24
- package/dist/runtime/react-plugin.d.ts +1 -1
- package/dist/runtime/vue-plugin.d.ts +1 -1
- package/dist/types-CHyDGt_C.d.ts +86 -0
- package/dist/utils/index.d.ts +59 -0
- package/dist/utils/index.js +190 -0
- package/package.json +8 -1
- package/src/types.ts +57 -12
- package/src/utils/index.ts +13 -0
- package/src/utils/translations.ts +311 -0
- package/src/vite-plugin.ts +329 -29
- package/dist/types-DwCG8sp8.d.ts +0 -48
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { L as LocaleTranslationPath, a as TranslationsConfig, b as TranslationCache } from '../types-CHyDGt_C.js';
|
|
2
|
+
|
|
3
|
+
type PathType = 'file' | 'folder' | 'glob' | 'array';
|
|
4
|
+
/**
|
|
5
|
+
* Detect the type of translation path
|
|
6
|
+
*/
|
|
7
|
+
declare function detectPathType(input: string | string[]): PathType;
|
|
8
|
+
/**
|
|
9
|
+
* Resolve a single translation path to an array of absolute file paths.
|
|
10
|
+
* Results are sorted alphabetically for predictable merge order.
|
|
11
|
+
*/
|
|
12
|
+
declare function resolveTranslationPaths(input: LocaleTranslationPath, projectRoot: string): Promise<string[]>;
|
|
13
|
+
/**
|
|
14
|
+
* Auto-discover translations from a base directory.
|
|
15
|
+
* Scans for locale folders (e.g., en/, es/, fr/) and their JSON files.
|
|
16
|
+
* Returns both discovered locales and their file mappings.
|
|
17
|
+
*/
|
|
18
|
+
declare function autoDiscoverTranslations(baseDir: string, projectRoot: string, configuredLocales?: string[]): Promise<{
|
|
19
|
+
locales: string[];
|
|
20
|
+
translations: Record<string, string[]>;
|
|
21
|
+
}>;
|
|
22
|
+
/**
|
|
23
|
+
* Resolve the full translations config to normalized form.
|
|
24
|
+
* Handles string (base dir), object (per-locale), or undefined (auto-discover).
|
|
25
|
+
*/
|
|
26
|
+
declare function resolveTranslationsConfig(config: TranslationsConfig | undefined, projectRoot: string, configuredLocales?: string[]): Promise<{
|
|
27
|
+
locales: string[];
|
|
28
|
+
translations: Record<string, string[]>;
|
|
29
|
+
}>;
|
|
30
|
+
/**
|
|
31
|
+
* Deep merge translation objects.
|
|
32
|
+
* - Objects are recursively merged
|
|
33
|
+
* - Arrays are REPLACED (not concatenated)
|
|
34
|
+
* - Primitives are overwritten by later values
|
|
35
|
+
* - Prototype pollution safe
|
|
36
|
+
*/
|
|
37
|
+
declare function deepMerge<T extends Record<string, unknown>>(target: T, ...sources: T[]): T;
|
|
38
|
+
/**
|
|
39
|
+
* Load cached translation discovery results
|
|
40
|
+
*/
|
|
41
|
+
declare function loadCache(projectRoot: string): TranslationCache | null;
|
|
42
|
+
/**
|
|
43
|
+
* Save translation discovery results to cache
|
|
44
|
+
*/
|
|
45
|
+
declare function saveCache(projectRoot: string, discovered: Record<string, string[]>): void;
|
|
46
|
+
/**
|
|
47
|
+
* Check if cache is still valid (files haven't changed)
|
|
48
|
+
*/
|
|
49
|
+
declare function isCacheValid(cache: TranslationCache, projectRoot: string): boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Convert an absolute path to a relative import path for Vite
|
|
52
|
+
*/
|
|
53
|
+
declare function toRelativeImport(absolutePath: string, projectRoot: string): string;
|
|
54
|
+
/**
|
|
55
|
+
* Generate a glob pattern for import.meta.glob from a base directory
|
|
56
|
+
*/
|
|
57
|
+
declare function toGlobPattern(baseDir: string, projectRoot: string): string;
|
|
58
|
+
|
|
59
|
+
export { type PathType, autoDiscoverTranslations, deepMerge, detectPathType, isCacheValid, loadCache, resolveTranslationPaths, resolveTranslationsConfig, saveCache, toGlobPattern, toRelativeImport };
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// src/utils/translations.ts
|
|
2
|
+
import { glob } from "tinyglobby";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
import * as fs from "fs";
|
|
5
|
+
var CACHE_FILE = ".ez-i18n.json";
|
|
6
|
+
var CACHE_VERSION = 1;
|
|
7
|
+
var DEFAULT_I18N_DIR = "./public/i18n";
|
|
8
|
+
function detectPathType(input) {
|
|
9
|
+
if (Array.isArray(input)) return "array";
|
|
10
|
+
if (input.includes("*")) return "glob";
|
|
11
|
+
if (input.endsWith("/") || input.endsWith(path.sep)) return "folder";
|
|
12
|
+
return "file";
|
|
13
|
+
}
|
|
14
|
+
function isDirectory(filePath) {
|
|
15
|
+
try {
|
|
16
|
+
return fs.statSync(filePath).isDirectory();
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
async function resolveTranslationPaths(input, projectRoot) {
|
|
22
|
+
const type = detectPathType(input);
|
|
23
|
+
let files = [];
|
|
24
|
+
switch (type) {
|
|
25
|
+
case "array":
|
|
26
|
+
for (const entry of input) {
|
|
27
|
+
const resolved = await resolveTranslationPaths(entry, projectRoot);
|
|
28
|
+
files.push(...resolved);
|
|
29
|
+
}
|
|
30
|
+
break;
|
|
31
|
+
case "glob":
|
|
32
|
+
files = await glob(input, {
|
|
33
|
+
cwd: projectRoot,
|
|
34
|
+
absolute: true
|
|
35
|
+
});
|
|
36
|
+
break;
|
|
37
|
+
case "folder": {
|
|
38
|
+
const folderPath = path.resolve(projectRoot, input.replace(/\/$/, ""));
|
|
39
|
+
files = await glob("**/*.json", {
|
|
40
|
+
cwd: folderPath,
|
|
41
|
+
absolute: true
|
|
42
|
+
});
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
case "file":
|
|
46
|
+
default: {
|
|
47
|
+
const filePath = path.resolve(projectRoot, input);
|
|
48
|
+
if (isDirectory(filePath)) {
|
|
49
|
+
files = await glob("**/*.json", {
|
|
50
|
+
cwd: filePath,
|
|
51
|
+
absolute: true
|
|
52
|
+
});
|
|
53
|
+
} else {
|
|
54
|
+
files = [filePath];
|
|
55
|
+
}
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return [...new Set(files)].sort((a, b) => a.localeCompare(b));
|
|
60
|
+
}
|
|
61
|
+
async function autoDiscoverTranslations(baseDir, projectRoot, configuredLocales) {
|
|
62
|
+
const absoluteBaseDir = path.resolve(projectRoot, baseDir.replace(/\/$/, ""));
|
|
63
|
+
if (!isDirectory(absoluteBaseDir)) {
|
|
64
|
+
console.warn(`[ez-i18n] Translation directory not found: ${absoluteBaseDir}`);
|
|
65
|
+
return { locales: configuredLocales || [], translations: {} };
|
|
66
|
+
}
|
|
67
|
+
const translations = {};
|
|
68
|
+
const discoveredLocales = [];
|
|
69
|
+
const entries = fs.readdirSync(absoluteBaseDir, { withFileTypes: true });
|
|
70
|
+
for (const entry of entries) {
|
|
71
|
+
if (entry.isDirectory()) {
|
|
72
|
+
const locale = entry.name;
|
|
73
|
+
if (configuredLocales && configuredLocales.length > 0) {
|
|
74
|
+
if (!configuredLocales.includes(locale)) continue;
|
|
75
|
+
}
|
|
76
|
+
const localePath = path.join(absoluteBaseDir, locale);
|
|
77
|
+
const files = await glob("**/*.json", {
|
|
78
|
+
cwd: localePath,
|
|
79
|
+
absolute: true
|
|
80
|
+
});
|
|
81
|
+
if (files.length > 0) {
|
|
82
|
+
discoveredLocales.push(locale);
|
|
83
|
+
translations[locale] = files.sort((a, b) => a.localeCompare(b));
|
|
84
|
+
}
|
|
85
|
+
} else if (entry.isFile() && entry.name.endsWith(".json")) {
|
|
86
|
+
const locale = path.basename(entry.name, ".json");
|
|
87
|
+
if (configuredLocales && configuredLocales.length > 0) {
|
|
88
|
+
if (!configuredLocales.includes(locale)) continue;
|
|
89
|
+
}
|
|
90
|
+
const filePath = path.join(absoluteBaseDir, entry.name);
|
|
91
|
+
if (!translations[locale]) {
|
|
92
|
+
discoveredLocales.push(locale);
|
|
93
|
+
translations[locale] = [];
|
|
94
|
+
}
|
|
95
|
+
translations[locale].push(filePath);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const sortedLocales = [...new Set(discoveredLocales)].sort();
|
|
99
|
+
return { locales: sortedLocales, translations };
|
|
100
|
+
}
|
|
101
|
+
async function resolveTranslationsConfig(config, projectRoot, configuredLocales) {
|
|
102
|
+
if (!config) {
|
|
103
|
+
return autoDiscoverTranslations(DEFAULT_I18N_DIR, projectRoot, configuredLocales);
|
|
104
|
+
}
|
|
105
|
+
if (typeof config === "string") {
|
|
106
|
+
return autoDiscoverTranslations(config, projectRoot, configuredLocales);
|
|
107
|
+
}
|
|
108
|
+
const translations = {};
|
|
109
|
+
const locales = Object.keys(config);
|
|
110
|
+
for (const [locale, localePath] of Object.entries(config)) {
|
|
111
|
+
translations[locale] = await resolveTranslationPaths(localePath, projectRoot);
|
|
112
|
+
}
|
|
113
|
+
return { locales, translations };
|
|
114
|
+
}
|
|
115
|
+
function deepMerge(target, ...sources) {
|
|
116
|
+
const FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
117
|
+
const result = { ...target };
|
|
118
|
+
for (const source of sources) {
|
|
119
|
+
if (!source || typeof source !== "object") continue;
|
|
120
|
+
for (const key of Object.keys(source)) {
|
|
121
|
+
if (FORBIDDEN_KEYS.has(key)) continue;
|
|
122
|
+
const targetVal = result[key];
|
|
123
|
+
const sourceVal = source[key];
|
|
124
|
+
if (sourceVal !== null && typeof sourceVal === "object" && !Array.isArray(sourceVal) && targetVal !== null && typeof targetVal === "object" && !Array.isArray(targetVal)) {
|
|
125
|
+
result[key] = deepMerge(
|
|
126
|
+
targetVal,
|
|
127
|
+
sourceVal
|
|
128
|
+
);
|
|
129
|
+
} else {
|
|
130
|
+
result[key] = sourceVal;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return result;
|
|
135
|
+
}
|
|
136
|
+
function loadCache(projectRoot) {
|
|
137
|
+
const cachePath = path.join(projectRoot, CACHE_FILE);
|
|
138
|
+
try {
|
|
139
|
+
if (!fs.existsSync(cachePath)) return null;
|
|
140
|
+
const content = fs.readFileSync(cachePath, "utf-8");
|
|
141
|
+
const cache = JSON.parse(content);
|
|
142
|
+
if (cache.version !== CACHE_VERSION) return null;
|
|
143
|
+
return cache;
|
|
144
|
+
} catch {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function saveCache(projectRoot, discovered) {
|
|
149
|
+
const cachePath = path.join(projectRoot, CACHE_FILE);
|
|
150
|
+
const cache = {
|
|
151
|
+
version: CACHE_VERSION,
|
|
152
|
+
discovered,
|
|
153
|
+
lastScan: (/* @__PURE__ */ new Date()).toISOString()
|
|
154
|
+
};
|
|
155
|
+
try {
|
|
156
|
+
fs.writeFileSync(cachePath, JSON.stringify(cache, null, 2));
|
|
157
|
+
} catch (error) {
|
|
158
|
+
console.warn("[ez-i18n] Failed to write cache file:", error);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function isCacheValid(cache, projectRoot) {
|
|
162
|
+
for (const files of Object.values(cache.discovered)) {
|
|
163
|
+
for (const file of files) {
|
|
164
|
+
if (!fs.existsSync(file)) return false;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
function toRelativeImport(absolutePath, projectRoot) {
|
|
170
|
+
const relativePath = path.relative(projectRoot, absolutePath);
|
|
171
|
+
const normalized = relativePath.replace(/\\/g, "/");
|
|
172
|
+
return normalized.startsWith(".") ? normalized : "./" + normalized;
|
|
173
|
+
}
|
|
174
|
+
function toGlobPattern(baseDir, projectRoot) {
|
|
175
|
+
const relativePath = path.relative(projectRoot, baseDir).replace(/\\/g, "/");
|
|
176
|
+
const normalized = relativePath.startsWith(".") ? relativePath : "./" + relativePath;
|
|
177
|
+
return `${normalized}/**/*.json`;
|
|
178
|
+
}
|
|
179
|
+
export {
|
|
180
|
+
autoDiscoverTranslations,
|
|
181
|
+
deepMerge,
|
|
182
|
+
detectPathType,
|
|
183
|
+
isCacheValid,
|
|
184
|
+
loadCache,
|
|
185
|
+
resolveTranslationPaths,
|
|
186
|
+
resolveTranslationsConfig,
|
|
187
|
+
saveCache,
|
|
188
|
+
toGlobPattern,
|
|
189
|
+
toRelativeImport
|
|
190
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zachhandley/ez-i18n",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -30,6 +30,10 @@
|
|
|
30
30
|
"./react": {
|
|
31
31
|
"types": "./dist/runtime/react-plugin.d.ts",
|
|
32
32
|
"import": "./dist/runtime/react-plugin.js"
|
|
33
|
+
},
|
|
34
|
+
"./utils": {
|
|
35
|
+
"types": "./dist/utils/index.d.ts",
|
|
36
|
+
"import": "./dist/utils/index.js"
|
|
33
37
|
}
|
|
34
38
|
},
|
|
35
39
|
"files": [
|
|
@@ -64,6 +68,9 @@
|
|
|
64
68
|
"bugs": {
|
|
65
69
|
"url": "https://github.com/zachhandley/ez-i18n/issues"
|
|
66
70
|
},
|
|
71
|
+
"dependencies": {
|
|
72
|
+
"tinyglobby": "^0.2.15"
|
|
73
|
+
},
|
|
67
74
|
"peerDependencies": {
|
|
68
75
|
"@nanostores/persistent": "^0.10.0",
|
|
69
76
|
"@nanostores/react": "^0.7.0 || ^0.8.0 || ^1.0.0",
|
package/src/types.ts
CHANGED
|
@@ -1,14 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Translation path for a single locale:
|
|
3
|
+
* - Single file: `./src/i18n/en.json`
|
|
4
|
+
* - Folder: `./src/i18n/en/` (auto-discover all JSONs inside)
|
|
5
|
+
* - Glob: `./src/i18n/en/**.json` (recursive)
|
|
6
|
+
* - Array: `['./common.json', './auth.json']`
|
|
7
|
+
*/
|
|
8
|
+
export type LocaleTranslationPath = string | string[];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Translation config can be:
|
|
12
|
+
* - A base directory string (auto-discovers locale folders): './public/i18n/'
|
|
13
|
+
* - Per-locale mapping: { en: './src/i18n/en/', es: './src/i18n/es.json' }
|
|
14
|
+
*/
|
|
15
|
+
export type TranslationsConfig = string | Record<string, LocaleTranslationPath>;
|
|
16
|
+
|
|
1
17
|
/**
|
|
2
18
|
* Configuration for ez-i18n Astro integration
|
|
3
19
|
*/
|
|
4
20
|
export interface EzI18nConfig {
|
|
5
21
|
/**
|
|
6
22
|
* List of supported locale codes (e.g., ['en', 'es', 'fr'])
|
|
23
|
+
* Optional if using directory-based auto-discovery - locales will be
|
|
24
|
+
* detected from folder names in the translations directory.
|
|
7
25
|
*/
|
|
8
|
-
locales
|
|
26
|
+
locales?: string[];
|
|
9
27
|
|
|
10
28
|
/**
|
|
11
|
-
* Default locale to use when no preference is detected
|
|
29
|
+
* Default locale to use when no preference is detected.
|
|
30
|
+
* Required - this tells us what to fall back to.
|
|
12
31
|
*/
|
|
13
32
|
defaultLocale: string;
|
|
14
33
|
|
|
@@ -19,26 +38,52 @@ export interface EzI18nConfig {
|
|
|
19
38
|
cookieName?: string;
|
|
20
39
|
|
|
21
40
|
/**
|
|
22
|
-
* Translation file paths
|
|
41
|
+
* Translation file paths configuration.
|
|
23
42
|
* Paths are relative to your project root.
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* es
|
|
29
|
-
*
|
|
43
|
+
*
|
|
44
|
+
* Can be:
|
|
45
|
+
* - A base directory (auto-discovers locale folders):
|
|
46
|
+
* translations: './public/i18n/'
|
|
47
|
+
* → Scans for en/, es/, fr/ folders and their JSON files
|
|
48
|
+
* → Auto-populates `locales` from discovered folders
|
|
49
|
+
*
|
|
50
|
+
* - Per-locale mapping with flexible path types:
|
|
51
|
+
* translations: {
|
|
52
|
+
* en: './src/i18n/en.json', // single file
|
|
53
|
+
* es: './src/i18n/es/', // folder (all JSONs)
|
|
54
|
+
* fr: './src/i18n/fr/**.json', // glob pattern
|
|
55
|
+
* de: ['./common.json', './auth.json'] // array of files
|
|
56
|
+
* }
|
|
57
|
+
*
|
|
58
|
+
* If not specified, auto-discovers from ./public/i18n/
|
|
30
59
|
*/
|
|
31
|
-
translations?:
|
|
60
|
+
translations?: TranslationsConfig;
|
|
32
61
|
}
|
|
33
62
|
|
|
34
63
|
/**
|
|
35
|
-
* Resolved config with defaults applied
|
|
64
|
+
* Resolved config with defaults applied.
|
|
65
|
+
* After resolution:
|
|
66
|
+
* - locales is always populated (from config or auto-discovered)
|
|
67
|
+
* - translations is normalized to arrays of absolute file paths
|
|
36
68
|
*/
|
|
37
69
|
export interface ResolvedEzI18nConfig {
|
|
38
70
|
locales: string[];
|
|
39
71
|
defaultLocale: string;
|
|
40
72
|
cookieName: string;
|
|
41
|
-
|
|
73
|
+
/** Normalized: locale → array of resolved absolute file paths */
|
|
74
|
+
translations: Record<string, string[]>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Cache file structure (.ez-i18n.json)
|
|
79
|
+
* Used to speed up subsequent builds by caching discovered translations
|
|
80
|
+
*/
|
|
81
|
+
export interface TranslationCache {
|
|
82
|
+
version: number;
|
|
83
|
+
/** Discovered locale → file paths mapping */
|
|
84
|
+
discovered: Record<string, string[]>;
|
|
85
|
+
/** ISO timestamp of last scan */
|
|
86
|
+
lastScan: string;
|
|
42
87
|
}
|
|
43
88
|
|
|
44
89
|
/**
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { glob } from 'tinyglobby';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import * as fs from 'node:fs';
|
|
4
|
+
import type { LocaleTranslationPath, TranslationsConfig, TranslationCache } from '../types';
|
|
5
|
+
|
|
6
|
+
const CACHE_FILE = '.ez-i18n.json';
|
|
7
|
+
const CACHE_VERSION = 1;
|
|
8
|
+
const DEFAULT_I18N_DIR = './public/i18n';
|
|
9
|
+
|
|
10
|
+
export type PathType = 'file' | 'folder' | 'glob' | 'array';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Detect the type of translation path
|
|
14
|
+
*/
|
|
15
|
+
export function detectPathType(input: string | string[]): PathType {
|
|
16
|
+
if (Array.isArray(input)) return 'array';
|
|
17
|
+
if (input.includes('*')) return 'glob';
|
|
18
|
+
if (input.endsWith('/') || input.endsWith(path.sep)) return 'folder';
|
|
19
|
+
return 'file';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Check if a path is a directory (handles missing trailing slash)
|
|
24
|
+
*/
|
|
25
|
+
function isDirectory(filePath: string): boolean {
|
|
26
|
+
try {
|
|
27
|
+
return fs.statSync(filePath).isDirectory();
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Resolve a single translation path to an array of absolute file paths.
|
|
35
|
+
* Results are sorted alphabetically for predictable merge order.
|
|
36
|
+
*/
|
|
37
|
+
export async function resolveTranslationPaths(
|
|
38
|
+
input: LocaleTranslationPath,
|
|
39
|
+
projectRoot: string
|
|
40
|
+
): Promise<string[]> {
|
|
41
|
+
const type = detectPathType(input);
|
|
42
|
+
let files: string[] = [];
|
|
43
|
+
|
|
44
|
+
switch (type) {
|
|
45
|
+
case 'array':
|
|
46
|
+
// Each entry could itself be a glob, folder, or file
|
|
47
|
+
for (const entry of input as string[]) {
|
|
48
|
+
const resolved = await resolveTranslationPaths(entry, projectRoot);
|
|
49
|
+
files.push(...resolved);
|
|
50
|
+
}
|
|
51
|
+
break;
|
|
52
|
+
|
|
53
|
+
case 'glob':
|
|
54
|
+
files = await glob(input as string, {
|
|
55
|
+
cwd: projectRoot,
|
|
56
|
+
absolute: true,
|
|
57
|
+
});
|
|
58
|
+
break;
|
|
59
|
+
|
|
60
|
+
case 'folder': {
|
|
61
|
+
const folderPath = path.resolve(projectRoot, (input as string).replace(/\/$/, ''));
|
|
62
|
+
files = await glob('**/*.json', {
|
|
63
|
+
cwd: folderPath,
|
|
64
|
+
absolute: true,
|
|
65
|
+
});
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
case 'file':
|
|
70
|
+
default: {
|
|
71
|
+
const filePath = path.resolve(projectRoot, input as string);
|
|
72
|
+
// Check if it's actually a directory (user omitted trailing slash)
|
|
73
|
+
if (isDirectory(filePath)) {
|
|
74
|
+
files = await glob('**/*.json', {
|
|
75
|
+
cwd: filePath,
|
|
76
|
+
absolute: true,
|
|
77
|
+
});
|
|
78
|
+
} else {
|
|
79
|
+
files = [filePath];
|
|
80
|
+
}
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Sort alphabetically for predictable merge order
|
|
86
|
+
return [...new Set(files)].sort((a, b) => a.localeCompare(b));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Auto-discover translations from a base directory.
|
|
91
|
+
* Scans for locale folders (e.g., en/, es/, fr/) and their JSON files.
|
|
92
|
+
* Returns both discovered locales and their file mappings.
|
|
93
|
+
*/
|
|
94
|
+
export async function autoDiscoverTranslations(
|
|
95
|
+
baseDir: string,
|
|
96
|
+
projectRoot: string,
|
|
97
|
+
configuredLocales?: string[]
|
|
98
|
+
): Promise<{ locales: string[]; translations: Record<string, string[]> }> {
|
|
99
|
+
const absoluteBaseDir = path.resolve(projectRoot, baseDir.replace(/\/$/, ''));
|
|
100
|
+
|
|
101
|
+
if (!isDirectory(absoluteBaseDir)) {
|
|
102
|
+
console.warn(`[ez-i18n] Translation directory not found: ${absoluteBaseDir}`);
|
|
103
|
+
return { locales: configuredLocales || [], translations: {} };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const translations: Record<string, string[]> = {};
|
|
107
|
+
const discoveredLocales: string[] = [];
|
|
108
|
+
|
|
109
|
+
// Read directory entries
|
|
110
|
+
const entries = fs.readdirSync(absoluteBaseDir, { withFileTypes: true });
|
|
111
|
+
|
|
112
|
+
for (const entry of entries) {
|
|
113
|
+
if (entry.isDirectory()) {
|
|
114
|
+
// This is a locale folder (e.g., en/, es/)
|
|
115
|
+
const locale = entry.name;
|
|
116
|
+
|
|
117
|
+
// If locales were configured, only include matching ones
|
|
118
|
+
if (configuredLocales && configuredLocales.length > 0) {
|
|
119
|
+
if (!configuredLocales.includes(locale)) continue;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const localePath = path.join(absoluteBaseDir, locale);
|
|
123
|
+
const files = await glob('**/*.json', {
|
|
124
|
+
cwd: localePath,
|
|
125
|
+
absolute: true,
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
if (files.length > 0) {
|
|
129
|
+
discoveredLocales.push(locale);
|
|
130
|
+
translations[locale] = files.sort((a, b) => a.localeCompare(b));
|
|
131
|
+
}
|
|
132
|
+
} else if (entry.isFile() && entry.name.endsWith('.json')) {
|
|
133
|
+
// Root-level JSON files (e.g., en.json, es.json)
|
|
134
|
+
// Extract locale from filename
|
|
135
|
+
const locale = path.basename(entry.name, '.json');
|
|
136
|
+
|
|
137
|
+
// If locales were configured, only include matching ones
|
|
138
|
+
if (configuredLocales && configuredLocales.length > 0) {
|
|
139
|
+
if (!configuredLocales.includes(locale)) continue;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const filePath = path.join(absoluteBaseDir, entry.name);
|
|
143
|
+
|
|
144
|
+
if (!translations[locale]) {
|
|
145
|
+
discoveredLocales.push(locale);
|
|
146
|
+
translations[locale] = [];
|
|
147
|
+
}
|
|
148
|
+
translations[locale].push(filePath);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Sort locales for consistency
|
|
153
|
+
const sortedLocales = [...new Set(discoveredLocales)].sort();
|
|
154
|
+
|
|
155
|
+
return { locales: sortedLocales, translations };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Resolve the full translations config to normalized form.
|
|
160
|
+
* Handles string (base dir), object (per-locale), or undefined (auto-discover).
|
|
161
|
+
*/
|
|
162
|
+
export async function resolveTranslationsConfig(
|
|
163
|
+
config: TranslationsConfig | undefined,
|
|
164
|
+
projectRoot: string,
|
|
165
|
+
configuredLocales?: string[]
|
|
166
|
+
): Promise<{ locales: string[]; translations: Record<string, string[]> }> {
|
|
167
|
+
// No config - auto-discover from default location
|
|
168
|
+
if (!config) {
|
|
169
|
+
return autoDiscoverTranslations(DEFAULT_I18N_DIR, projectRoot, configuredLocales);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// String - treat as base directory for auto-discovery
|
|
173
|
+
if (typeof config === 'string') {
|
|
174
|
+
return autoDiscoverTranslations(config, projectRoot, configuredLocales);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Object - per-locale mapping
|
|
178
|
+
const translations: Record<string, string[]> = {};
|
|
179
|
+
const locales = Object.keys(config);
|
|
180
|
+
|
|
181
|
+
for (const [locale, localePath] of Object.entries(config)) {
|
|
182
|
+
translations[locale] = await resolveTranslationPaths(localePath, projectRoot);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return { locales, translations };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Deep merge translation objects.
|
|
190
|
+
* - Objects are recursively merged
|
|
191
|
+
* - Arrays are REPLACED (not concatenated)
|
|
192
|
+
* - Primitives are overwritten by later values
|
|
193
|
+
* - Prototype pollution safe
|
|
194
|
+
*/
|
|
195
|
+
export function deepMerge<T extends Record<string, unknown>>(
|
|
196
|
+
target: T,
|
|
197
|
+
...sources: T[]
|
|
198
|
+
): T {
|
|
199
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
200
|
+
const result = { ...target };
|
|
201
|
+
|
|
202
|
+
for (const source of sources) {
|
|
203
|
+
if (!source || typeof source !== 'object') continue;
|
|
204
|
+
|
|
205
|
+
for (const key of Object.keys(source)) {
|
|
206
|
+
if (FORBIDDEN_KEYS.has(key)) continue;
|
|
207
|
+
|
|
208
|
+
const targetVal = result[key as keyof T];
|
|
209
|
+
const sourceVal = source[key as keyof T];
|
|
210
|
+
|
|
211
|
+
if (
|
|
212
|
+
sourceVal !== null &&
|
|
213
|
+
typeof sourceVal === 'object' &&
|
|
214
|
+
!Array.isArray(sourceVal) &&
|
|
215
|
+
targetVal !== null &&
|
|
216
|
+
typeof targetVal === 'object' &&
|
|
217
|
+
!Array.isArray(targetVal)
|
|
218
|
+
) {
|
|
219
|
+
// Both are plain objects - recurse
|
|
220
|
+
(result as Record<string, unknown>)[key] = deepMerge(
|
|
221
|
+
targetVal as Record<string, unknown>,
|
|
222
|
+
sourceVal as Record<string, unknown>
|
|
223
|
+
);
|
|
224
|
+
} else {
|
|
225
|
+
// Arrays replace, primitives overwrite
|
|
226
|
+
(result as Record<string, unknown>)[key] = sourceVal;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return result;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Load cached translation discovery results
|
|
236
|
+
*/
|
|
237
|
+
export function loadCache(projectRoot: string): TranslationCache | null {
|
|
238
|
+
const cachePath = path.join(projectRoot, CACHE_FILE);
|
|
239
|
+
|
|
240
|
+
try {
|
|
241
|
+
if (!fs.existsSync(cachePath)) return null;
|
|
242
|
+
|
|
243
|
+
const content = fs.readFileSync(cachePath, 'utf-8');
|
|
244
|
+
const cache = JSON.parse(content) as TranslationCache;
|
|
245
|
+
|
|
246
|
+
// Validate cache version
|
|
247
|
+
if (cache.version !== CACHE_VERSION) return null;
|
|
248
|
+
|
|
249
|
+
return cache;
|
|
250
|
+
} catch {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Save translation discovery results to cache
|
|
257
|
+
*/
|
|
258
|
+
export function saveCache(
|
|
259
|
+
projectRoot: string,
|
|
260
|
+
discovered: Record<string, string[]>
|
|
261
|
+
): void {
|
|
262
|
+
const cachePath = path.join(projectRoot, CACHE_FILE);
|
|
263
|
+
|
|
264
|
+
const cache: TranslationCache = {
|
|
265
|
+
version: CACHE_VERSION,
|
|
266
|
+
discovered,
|
|
267
|
+
lastScan: new Date().toISOString(),
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
try {
|
|
271
|
+
fs.writeFileSync(cachePath, JSON.stringify(cache, null, 2));
|
|
272
|
+
} catch (error) {
|
|
273
|
+
console.warn('[ez-i18n] Failed to write cache file:', error);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Check if cache is still valid (files haven't changed)
|
|
279
|
+
*/
|
|
280
|
+
export function isCacheValid(
|
|
281
|
+
cache: TranslationCache,
|
|
282
|
+
projectRoot: string
|
|
283
|
+
): boolean {
|
|
284
|
+
// Check if all cached files still exist
|
|
285
|
+
for (const files of Object.values(cache.discovered)) {
|
|
286
|
+
for (const file of files) {
|
|
287
|
+
if (!fs.existsSync(file)) return false;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Convert an absolute path to a relative import path for Vite
|
|
296
|
+
*/
|
|
297
|
+
export function toRelativeImport(absolutePath: string, projectRoot: string): string {
|
|
298
|
+
const relativePath = path.relative(projectRoot, absolutePath);
|
|
299
|
+
// Ensure it starts with ./ and uses forward slashes
|
|
300
|
+
const normalized = relativePath.replace(/\\/g, '/');
|
|
301
|
+
return normalized.startsWith('.') ? normalized : './' + normalized;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Generate a glob pattern for import.meta.glob from a base directory
|
|
306
|
+
*/
|
|
307
|
+
export function toGlobPattern(baseDir: string, projectRoot: string): string {
|
|
308
|
+
const relativePath = path.relative(projectRoot, baseDir).replace(/\\/g, '/');
|
|
309
|
+
const normalized = relativePath.startsWith('.') ? relativePath : './' + relativePath;
|
|
310
|
+
return `${normalized}/**/*.json`;
|
|
311
|
+
}
|