locale-keysmith 0.1.0 → 0.3.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/README.md +287 -20
- package/dist/checks.d.ts +30 -0
- package/dist/checks.js +130 -0
- package/dist/checks.js.map +1 -0
- package/dist/cli.js +333 -79
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +8 -0
- package/dist/config.js +107 -20
- package/dist/config.js.map +1 -1
- package/dist/glob.d.ts +2 -0
- package/dist/glob.js +6 -0
- package/dist/glob.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts +13 -0
- package/dist/init.js +55 -0
- package/dist/init.js.map +1 -0
- package/dist/keys.d.ts +5 -0
- package/dist/keys.js +68 -23
- package/dist/keys.js.map +1 -1
- package/dist/locale-path.d.ts +20 -0
- package/dist/locale-path.js +57 -0
- package/dist/locale-path.js.map +1 -0
- package/dist/parser.js +89 -8
- package/dist/parser.js.map +1 -1
- package/dist/scanner.d.ts +22 -0
- package/dist/scanner.js +39 -8
- package/dist/scanner.js.map +1 -1
- package/dist/translate.d.ts +22 -1
- package/dist/translate.js +159 -19
- package/dist/translate.js.map +1 -1
- package/dist/types.d.ts +3 -0
- package/dist/usage.d.ts +16 -0
- package/dist/usage.js +73 -17
- package/dist/usage.js.map +1 -1
- package/package.json +41 -17
package/dist/config.js
CHANGED
|
@@ -1,25 +1,112 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
3
|
+
import { isLocaleCode } from "./locale-path.js";
|
|
4
|
+
export const CONFIG_FILENAME = "locale-keysmith.config.json";
|
|
5
|
+
export const LOCALE_EXTENSIONS = ["json", "yml", "yaml"];
|
|
6
|
+
export const SOURCE_EXTENSIONS = ["ts", "tsx", "js", "jsx", "mjs", "cjs", "vue", "svelte"];
|
|
7
|
+
const DEFAULT_ROOTS = ["src"];
|
|
8
|
+
const STRING_LIST_FIELDS = ["roots", "translationFiles", "src", "ignoreKeys"];
|
|
9
|
+
// `$schema` is accepted so editors can attach a JSON schema to the file.
|
|
10
|
+
const KNOWN_FIELDS = ["$schema", "sourceLocale", ...STRING_LIST_FIELDS];
|
|
11
|
+
function rootGlob(root, extensions) {
|
|
12
|
+
const clean = root.replace(/^\.\/+/, "").replace(/\/+$/, "");
|
|
13
|
+
const prefix = clean === "" || clean === "." ? "" : `${clean}/`;
|
|
14
|
+
return `${prefix}**/*.{${extensions.join(",")}}`;
|
|
15
|
+
}
|
|
13
16
|
export function loadConfig(cwd = process.cwd()) {
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
17
|
+
const userConfig = readUserConfig(join(cwd, CONFIG_FILENAME));
|
|
18
|
+
const roots = userConfig.roots ?? DEFAULT_ROOTS;
|
|
19
|
+
return structuredClone({
|
|
20
|
+
sourceLocale: userConfig.sourceLocale ?? "en",
|
|
21
|
+
roots,
|
|
22
|
+
translationFiles: userConfig.translationFiles ?? roots.map((root) => rootGlob(root, LOCALE_EXTENSIONS)),
|
|
23
|
+
src: userConfig.src ?? roots.map((root) => rootGlob(root, SOURCE_EXTENSIONS)),
|
|
24
|
+
ignoreKeys: userConfig.ignoreKeys ?? []
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Checks a parsed config file and returns it typed, or throws one error that lists every
|
|
29
|
+
* problem, so a typo like `"roots": "src"` fails up front instead of deep inside a command.
|
|
30
|
+
*/
|
|
31
|
+
export function validateConfig(value) {
|
|
32
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
33
|
+
throw new Error(`Invalid ${CONFIG_FILENAME}: expected a JSON object, found ${describe(value)}.`);
|
|
34
|
+
}
|
|
35
|
+
const config = value;
|
|
36
|
+
const problems = [];
|
|
37
|
+
for (const field of Object.keys(config)) {
|
|
38
|
+
if (!KNOWN_FIELDS.includes(field)) {
|
|
39
|
+
const suggestion = closestField(field);
|
|
40
|
+
problems.push(`unknown field "${field}"${suggestion ? ` (did you mean "${suggestion}"?)` : ""}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if ("sourceLocale" in config) {
|
|
44
|
+
const locale = config.sourceLocale;
|
|
45
|
+
if (typeof locale !== "string") {
|
|
46
|
+
problems.push(`"sourceLocale" must be a string such as "en", found ${describe(locale)}`);
|
|
47
|
+
}
|
|
48
|
+
else if (!isLocaleCode(locale)) {
|
|
49
|
+
problems.push(`"sourceLocale" must be a locale code such as "en" or "pt-BR", found "${locale}"`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
for (const field of STRING_LIST_FIELDS) {
|
|
53
|
+
if (!(field in config)) {
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
const list = config[field];
|
|
57
|
+
if (typeof list === "string") {
|
|
58
|
+
problems.push(`"${field}" must be an array of strings: use ["${list}"] instead of "${list}"`);
|
|
59
|
+
}
|
|
60
|
+
else if (!Array.isArray(list) || list.some((item) => typeof item !== "string" || item.trim() === "")) {
|
|
61
|
+
problems.push(`"${field}" must be an array of non-empty strings, found ${describe(list)}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (problems.length > 0) {
|
|
65
|
+
throw new Error(`Invalid ${CONFIG_FILENAME}:\n${problems.map((problem) => ` - ${problem}`).join("\n")}`);
|
|
66
|
+
}
|
|
67
|
+
return config;
|
|
68
|
+
}
|
|
69
|
+
function readUserConfig(path) {
|
|
70
|
+
if (!existsSync(path)) {
|
|
71
|
+
return {};
|
|
72
|
+
}
|
|
73
|
+
let parsed;
|
|
74
|
+
try {
|
|
75
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
79
|
+
throw new Error(`Failed to parse ${CONFIG_FILENAME}: ${detail}`, { cause: error });
|
|
80
|
+
}
|
|
81
|
+
return validateConfig(parsed);
|
|
82
|
+
}
|
|
83
|
+
function describe(value) {
|
|
84
|
+
if (Array.isArray(value)) {
|
|
85
|
+
return `${JSON.stringify(value)}`;
|
|
86
|
+
}
|
|
87
|
+
if (value === null) {
|
|
88
|
+
return "null";
|
|
89
|
+
}
|
|
90
|
+
return typeof value === "string" ? `"${value}"` : `${typeof value} ${JSON.stringify(value)}`;
|
|
91
|
+
}
|
|
92
|
+
/** A known field within two edits of `field` (case-insensitive), to catch typos. */
|
|
93
|
+
function closestField(field) {
|
|
94
|
+
const candidates = KNOWN_FIELDS.map((known) => ({ known, distance: editDistance(field, known) }));
|
|
95
|
+
const best = candidates.sort((a, b) => a.distance - b.distance)[0];
|
|
96
|
+
return best.distance <= 2 ? best.known : undefined;
|
|
97
|
+
}
|
|
98
|
+
function editDistance(a, b) {
|
|
99
|
+
const left = a.toLowerCase();
|
|
100
|
+
const right = b.toLowerCase();
|
|
101
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
102
|
+
for (let i = 1; i <= left.length; i += 1) {
|
|
103
|
+
const current = [i];
|
|
104
|
+
for (let j = 1; j <= right.length; j += 1) {
|
|
105
|
+
const cost = left[i - 1] === right[j - 1] ? 0 : 1;
|
|
106
|
+
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
|
|
107
|
+
}
|
|
108
|
+
previous = current;
|
|
109
|
+
}
|
|
110
|
+
return previous[right.length];
|
|
24
111
|
}
|
|
25
112
|
//# sourceMappingURL=config.js.map
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","s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,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAClD,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;QACrF,CAAC;QAED,QAAQ,GAAG,OAAO,CAAC;IACrB,CAAC;IAED,OAAO,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC"}
|
package/dist/glob.d.ts
ADDED
package/dist/glob.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import fg from "fast-glob";
|
|
2
|
+
export const IGNORED_DIRECTORIES = ["**/node_modules/**", "**/dist/**", "**/.next/**"];
|
|
3
|
+
export function globFiles(patterns, cwd = process.cwd(), extraIgnore = []) {
|
|
4
|
+
return fg(patterns, { cwd, absolute: true, ignore: [...IGNORED_DIRECTORIES, ...extraIgnore] });
|
|
5
|
+
}
|
|
6
|
+
//# sourceMappingURL=glob.js.map
|
package/dist/glob.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"glob.js","sourceRoot":"","sources":["../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,WAAW,CAAC;AAE3B,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,oBAAoB,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;AAEvF,MAAM,UAAU,SAAS,CACvB,QAAkB,EAClB,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,EACnB,cAAwB,EAAE;IAE1B,OAAO,EAAE,CAAC,QAAQ,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,GAAG,mBAAmB,EAAE,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC;AACjG,CAAC"}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,CAAC;AACvB,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC"}
|
package/dist/init.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface StarterConfig {
|
|
2
|
+
sourceLocale: string;
|
|
3
|
+
roots: string[];
|
|
4
|
+
ignoreKeys: string[];
|
|
5
|
+
}
|
|
6
|
+
export interface Detection {
|
|
7
|
+
config: StarterConfig;
|
|
8
|
+
/** Locale files found, relative to the project. */
|
|
9
|
+
localeFiles: string[];
|
|
10
|
+
locales: string[];
|
|
11
|
+
}
|
|
12
|
+
/** Builds a starter config from the locale files and source folders found in `cwd`. */
|
|
13
|
+
export declare function detectConfig(cwd?: string): Promise<Detection>;
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { existsSync, statSync } from "node:fs";
|
|
2
|
+
import { join, relative, sep } from "node:path";
|
|
3
|
+
import { CONFIG_FILENAME, LOCALE_EXTENSIONS } from "./config.js";
|
|
4
|
+
import { globFiles } from "./glob.js";
|
|
5
|
+
import { flattenKeys } from "./keys.js";
|
|
6
|
+
import { parseLocalePath } from "./locale-path.js";
|
|
7
|
+
import { readLocaleFile } from "./parser.js";
|
|
8
|
+
/** Folders that usually hold application source code. */
|
|
9
|
+
const SOURCE_DIRECTORIES = ["src", "app", "pages", "components", "lib", "packages"];
|
|
10
|
+
/** Locale files in these folders are test data, not the project's translations. */
|
|
11
|
+
const IGNORED_FOR_DETECTION = [
|
|
12
|
+
"**/{test,tests,__tests__,fixtures,__fixtures__,e2e,coverage}/**",
|
|
13
|
+
`**/${CONFIG_FILENAME}`
|
|
14
|
+
];
|
|
15
|
+
/** Builds a starter config from the locale files and source folders found in `cwd`. */
|
|
16
|
+
export async function detectConfig(cwd = process.cwd()) {
|
|
17
|
+
const paths = await globFiles([`**/*.{${LOCALE_EXTENSIONS.join(",")}}`], cwd, IGNORED_FOR_DETECTION);
|
|
18
|
+
const localePaths = paths.filter((path) => parseLocalePath(path) !== undefined).sort();
|
|
19
|
+
const localeFiles = localePaths.map((path) => relative(cwd, path));
|
|
20
|
+
const locales = [...new Set(localePaths.map((path) => parseLocalePath(path)?.locale))].sort();
|
|
21
|
+
const localeRoots = localeFiles.map((path) => (path.includes(sep) ? path.split(sep)[0] : "."));
|
|
22
|
+
const sourceRoots = SOURCE_DIRECTORIES.filter((name) => isDirectory(join(cwd, name)));
|
|
23
|
+
const roots = [...new Set([...localeRoots, ...sourceRoots])].sort();
|
|
24
|
+
return {
|
|
25
|
+
config: {
|
|
26
|
+
sourceLocale: pickSourceLocale(localePaths, locales),
|
|
27
|
+
roots: roots.length > 0 ? roots : ["src"],
|
|
28
|
+
ignoreKeys: []
|
|
29
|
+
},
|
|
30
|
+
localeFiles,
|
|
31
|
+
locales
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** `en` (or an English variant) when present, otherwise the locale with the most keys. */
|
|
35
|
+
function pickSourceLocale(paths, locales) {
|
|
36
|
+
const english = locales.find((locale) => locale === "en") ?? locales.find((locale) => /^en[-_]/i.test(locale));
|
|
37
|
+
if (english || locales.length === 0) {
|
|
38
|
+
return english ?? "en";
|
|
39
|
+
}
|
|
40
|
+
const keyCounts = new Map();
|
|
41
|
+
for (const path of paths) {
|
|
42
|
+
const locale = parseLocalePath(path)?.locale;
|
|
43
|
+
try {
|
|
44
|
+
keyCounts.set(locale, (keyCounts.get(locale) ?? 0) + flattenKeys(readLocaleFile(path).data).length);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// An unreadable file just does not count towards its locale.
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return locales.reduce((best, locale) => (keyCounts.get(locale) ?? 0) > (keyCounts.get(best) ?? 0) ? locale : best);
|
|
51
|
+
}
|
|
52
|
+
function isDirectory(path) {
|
|
53
|
+
return existsSync(path) && statSync(path).isDirectory();
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=init.js.map
|
package/dist/init.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE1C,yDAAyD;AACzD,MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC;AAEpF,mFAAmF;AACnF,MAAM,qBAAqB,GAAG;IAC5B,iEAAiE;IACjE,MAAM,eAAe,EAAE;CACxB,CAAC;AAeF,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE;IACpD,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,CAAC,SAAS,iBAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,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I,CAAC,CAAC,WAAW,EAAE,CAAC;AAC1D,CAAC"}
|
package/dist/keys.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import type { LocaleObject, LocaleValue } from "./types.js";
|
|
2
|
+
export declare function isSorted(value: LocaleObject): boolean;
|
|
2
3
|
export declare function sortObjectKeys<T extends LocaleValue>(value: T): T;
|
|
4
|
+
/**
|
|
5
|
+
* Every key path in the file, once each. `{ "a.b": "x", "a": { "b": "y" } }` writes `a.b`
|
|
6
|
+
* twice but i18next sees one key, so it is listed once (`duplicateKeys` reports it).
|
|
7
|
+
*/
|
|
3
8
|
export declare function flattenKeys(value: LocaleObject, prefix?: string): string[];
|
|
4
9
|
export declare function filterIgnoredKeys(keys: string[], ignorePatterns: string[]): string[];
|
|
5
10
|
export declare function getValueByPath(value: LocaleObject, path: string): LocaleValue | undefined;
|
package/dist/keys.js
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
+
// A fixed collator keeps the sort order identical on every machine; the default
|
|
2
|
+
// `localeCompare()` follows the runtime locale, so CI and laptops could disagree.
|
|
3
|
+
const collator = new Intl.Collator("en");
|
|
4
|
+
export function isSorted(value) {
|
|
5
|
+
return JSON.stringify(value) === JSON.stringify(sortObjectKeys(value));
|
|
6
|
+
}
|
|
1
7
|
export function sortObjectKeys(value) {
|
|
2
8
|
if (Array.isArray(value)) {
|
|
3
9
|
return value.map((item) => sortObjectKeys(item));
|
|
4
10
|
}
|
|
5
11
|
if (isPlainObject(value)) {
|
|
6
12
|
const sorted = Object.keys(value)
|
|
7
|
-
.sort(
|
|
13
|
+
.sort(collator.compare)
|
|
8
14
|
.reduce((result, key) => {
|
|
9
15
|
result[key] = sortObjectKeys(value[key]);
|
|
10
16
|
return result;
|
|
@@ -13,30 +19,35 @@ export function sortObjectKeys(value) {
|
|
|
13
19
|
}
|
|
14
20
|
return value;
|
|
15
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Every key path in the file, once each. `{ "a.b": "x", "a": { "b": "y" } }` writes `a.b`
|
|
24
|
+
* twice but i18next sees one key, so it is listed once (`duplicateKeys` reports it).
|
|
25
|
+
*/
|
|
16
26
|
export function flattenKeys(value, prefix = "") {
|
|
17
|
-
return
|
|
18
|
-
const path = prefix ? `${prefix}.${key}` : key;
|
|
19
|
-
if (isPlainObject(child)) {
|
|
20
|
-
return flattenKeys(child, path);
|
|
21
|
-
}
|
|
22
|
-
return [path];
|
|
23
|
-
});
|
|
27
|
+
return [...new Set(keyPaths(value, prefix))];
|
|
24
28
|
}
|
|
25
29
|
export function filterIgnoredKeys(keys, ignorePatterns) {
|
|
26
|
-
if (ignorePatterns.length === 0)
|
|
30
|
+
if (ignorePatterns.length === 0) {
|
|
27
31
|
return keys;
|
|
32
|
+
}
|
|
28
33
|
const matchers = ignorePatterns.map(patternToRegExp);
|
|
29
34
|
return keys.filter((key) => !matchers.some((matcher) => matcher.test(key)));
|
|
30
35
|
}
|
|
31
36
|
export function getValueByPath(value, path) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
+
const chain = findKeyChain(value, path.split("."));
|
|
38
|
+
if (!chain) {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
return chain.reduce((current, key) => current[key], value);
|
|
37
42
|
}
|
|
38
43
|
export function setValueByPath(value, path, nextValue) {
|
|
39
44
|
const segments = path.split(".");
|
|
45
|
+
const existing = findKeyChain(value, segments);
|
|
46
|
+
if (existing) {
|
|
47
|
+
const parent = existing.slice(0, -1).reduce((current, key) => current[key], value);
|
|
48
|
+
parent[existing.at(-1)] = nextValue;
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
40
51
|
let current = value;
|
|
41
52
|
for (const segment of segments.slice(0, -1)) {
|
|
42
53
|
const child = current[segment];
|
|
@@ -48,17 +59,17 @@ export function setValueByPath(value, path, nextValue) {
|
|
|
48
59
|
current[segments.at(-1)] = nextValue;
|
|
49
60
|
}
|
|
50
61
|
export function deleteValueByPath(value, path) {
|
|
51
|
-
const
|
|
52
|
-
|
|
62
|
+
const chain = findKeyChain(value, path.split("."));
|
|
63
|
+
if (!chain) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
53
66
|
const parents = [];
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
parents.push({ object: current, key: segment });
|
|
59
|
-
current = child;
|
|
67
|
+
let current = value;
|
|
68
|
+
for (const key of chain.slice(0, -1)) {
|
|
69
|
+
parents.push({ object: current, key });
|
|
70
|
+
current = current[key];
|
|
60
71
|
}
|
|
61
|
-
delete current[
|
|
72
|
+
delete current[chain.at(-1)];
|
|
62
73
|
for (const parent of parents.reverse()) {
|
|
63
74
|
const child = parent.object[parent.key];
|
|
64
75
|
if (isPlainObject(child) && Object.keys(child).length === 0) {
|
|
@@ -66,6 +77,40 @@ export function deleteValueByPath(value, path) {
|
|
|
66
77
|
}
|
|
67
78
|
}
|
|
68
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* Resolves a dotted path to the actual object keys it refers to. A key may itself
|
|
82
|
+
* contain dots (`{ "a.b": "x" }`), so `a.b` can mean `a` → `b` or the single key
|
|
83
|
+
* `a.b`; like i18next, nesting is tried first and joined segments second.
|
|
84
|
+
*/
|
|
85
|
+
function findKeyChain(value, segments) {
|
|
86
|
+
for (let size = 1; size <= segments.length; size += 1) {
|
|
87
|
+
const key = segments.slice(0, size).join(".");
|
|
88
|
+
if (!Object.hasOwn(value, key)) {
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const rest = segments.slice(size);
|
|
92
|
+
if (rest.length === 0) {
|
|
93
|
+
return [key];
|
|
94
|
+
}
|
|
95
|
+
const child = value[key];
|
|
96
|
+
if (isPlainObject(child)) {
|
|
97
|
+
const chain = findKeyChain(child, rest);
|
|
98
|
+
if (chain) {
|
|
99
|
+
return [key, ...chain];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
function keyPaths(value, prefix) {
|
|
106
|
+
return Object.entries(value).flatMap(([key, child]) => {
|
|
107
|
+
const path = prefix ? `${prefix}.${key}` : key;
|
|
108
|
+
if (isPlainObject(child)) {
|
|
109
|
+
return keyPaths(child, path);
|
|
110
|
+
}
|
|
111
|
+
return [path];
|
|
112
|
+
});
|
|
113
|
+
}
|
|
69
114
|
function isPlainObject(value) {
|
|
70
115
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
71
116
|
}
|
package/dist/keys.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,cAAc,CAAwB,KAAQ;IAC5D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,CAAM,CAAC;IACxD,CAAC;IAED,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC;aAC9B,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAEA,gFAAgF;AAChF,kFAAkF;AAClF,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAEzC,MAAM,UAAU,QAAQ,CAAC,KAAmB;IAC1C,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC;AACzE,CAAC;AAED,MAAM,UAAU,cAAc,CAAwB,KAAQ;IAC5D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;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e,CAAC,OAAe;IACtC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAEpF,OAAO,IAAI,MAAM,CAAC,IAAI,OAAO,GAAG,CAAC,CAAC;AACpC,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface LocalePath {
|
|
2
|
+
locale: string;
|
|
3
|
+
/** For `locales/en/common.json` layouts: the file name without extension (`common`). */
|
|
4
|
+
namespace?: string;
|
|
5
|
+
/**
|
|
6
|
+
* Files with the same group are translations of each other. `locales/en.json` and
|
|
7
|
+
* `locales/de.json` share `locales`; `locales/en/common.json` and `locales/de/common.json`
|
|
8
|
+
* share `locales/{locale}/common`.
|
|
9
|
+
*/
|
|
10
|
+
group: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function isLocaleCode(name: string): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Works out which locale a file holds, from its name (`locales/pt-BR.json`) or, for the
|
|
15
|
+
* i18next-http-backend layout, from its directory (`public/locales/pt-BR/common.json`).
|
|
16
|
+
* Returns undefined when neither looks like a locale code (e.g. `src/data/config.json`).
|
|
17
|
+
*/
|
|
18
|
+
export declare function parseLocalePath(path: string): LocalePath | undefined;
|
|
19
|
+
/** Path of the `locale` counterpart of a locale file, e.g. `locales/de.json` for `locales/en.json`. */
|
|
20
|
+
export declare function localeFilePath(path: string, locale: string): string;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { basename, dirname, extname, join } from "node:path";
|
|
2
|
+
// language[-Script][-REGION], with `-` or `_`: en, pt-BR, zh-Hant, sr_Latn_RS, es-419.
|
|
3
|
+
const localeShape = /^([a-z]{2,3})(?:[-_][a-z]{4})?(?:[-_](?:[a-z]{2}|\d{3}))?$/i;
|
|
4
|
+
// Valid language codes that are far more often a folder or file name in a project.
|
|
5
|
+
const notLocales = new Set([
|
|
6
|
+
"bak",
|
|
7
|
+
"bar",
|
|
8
|
+
"bin",
|
|
9
|
+
"crm",
|
|
10
|
+
"del",
|
|
11
|
+
"ext",
|
|
12
|
+
"mac",
|
|
13
|
+
"nav",
|
|
14
|
+
"new",
|
|
15
|
+
"run",
|
|
16
|
+
"src",
|
|
17
|
+
"swc"
|
|
18
|
+
]);
|
|
19
|
+
const languageNames = new Intl.DisplayNames(["en"], { type: "language", fallback: "none" });
|
|
20
|
+
export function isLocaleCode(name) {
|
|
21
|
+
const language = localeShape.exec(name)?.[1].toLowerCase();
|
|
22
|
+
if (!language || notLocales.has(language)) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
return languageNames.of(language) !== undefined;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Works out which locale a file holds, from its name (`locales/pt-BR.json`) or, for the
|
|
34
|
+
* i18next-http-backend layout, from its directory (`public/locales/pt-BR/common.json`).
|
|
35
|
+
* Returns undefined when neither looks like a locale code (e.g. `src/data/config.json`).
|
|
36
|
+
*/
|
|
37
|
+
export function parseLocalePath(path) {
|
|
38
|
+
const name = basename(path, extname(path));
|
|
39
|
+
const directory = dirname(path);
|
|
40
|
+
if (isLocaleCode(name)) {
|
|
41
|
+
return { locale: name, group: directory };
|
|
42
|
+
}
|
|
43
|
+
const parent = basename(directory);
|
|
44
|
+
if (isLocaleCode(parent)) {
|
|
45
|
+
return { locale: parent, namespace: name, group: join(dirname(directory), "{locale}", name) };
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
/** Path of the `locale` counterpart of a locale file, e.g. `locales/de.json` for `locales/en.json`. */
|
|
50
|
+
export function localeFilePath(path, locale) {
|
|
51
|
+
const parsed = parseLocalePath(path);
|
|
52
|
+
if (parsed?.namespace !== undefined) {
|
|
53
|
+
return join(dirname(dirname(path)), locale, basename(path));
|
|
54
|
+
}
|
|
55
|
+
return join(dirname(path), `${locale}${extname(path)}`);
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=locale-path.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"locale-path.js","sourceRoot":"","sources":["../src/locale-path.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAc7D,uFAAuF;AACvF,MAAM,WAAW,GAAG,6DAA6D,CAAC;AAElF,mFAAmF;AACnF,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;CACN,CAAC,CAAC;AAEH,MAAM,aAAa,GAAG,IAAI,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;AAE5F,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,QAAQ,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;IAE3D,IAAI,CAAC,QAAQ,IAAI,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1C,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,CAAC;QACH,OAAO,aAAa,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,SAAS,CAAC;IAClD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3C,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEhC,IAAI,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;QACvB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;IAC5C,CAAC;IAED,MAAM,MAAM,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC;IAEnC,IAAI,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;QACzB,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,CAAC;IAChG,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,cAAc,CAAC,IAAY,EAAE,MAAc;IACzD,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAErC,IAAI,MAAM,EAAE,SAAS,KAAK,SAAS,EAAE,CAAC;QACpC,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC1D,CAAC"}
|
package/dist/parser.js
CHANGED
|
@@ -1,26 +1,107 @@
|
|
|
1
1
|
import { extname } from "node:path";
|
|
2
2
|
import { readFileSync, writeFileSync } from "node:fs";
|
|
3
3
|
import YAML from "yaml";
|
|
4
|
+
import { parseLocalePath } from "./locale-path.js";
|
|
4
5
|
export function readLocaleFile(path) {
|
|
5
|
-
const
|
|
6
|
+
const format = extname(path).toLowerCase() === ".json" ? "json" : "yaml";
|
|
6
7
|
const raw = readFileSync(path, "utf8");
|
|
7
|
-
|
|
8
|
-
|
|
8
|
+
let parsed = {};
|
|
9
|
+
if (raw.trim() !== "") {
|
|
10
|
+
try {
|
|
11
|
+
parsed = format === "json" ? JSON.parse(raw) : YAML.parse(raw);
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
15
|
+
throw new Error(`Failed to parse ${path}: ${detail}`, { cause: error });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
parsed ??= {};
|
|
19
|
+
if (typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
20
|
+
const found = Array.isArray(parsed) ? "an array" : `a ${typeof parsed}`;
|
|
21
|
+
throw new Error(`Expected ${path} to contain an object of translation keys, but found ${found}.`);
|
|
22
|
+
}
|
|
9
23
|
return {
|
|
10
24
|
path,
|
|
11
25
|
locale: inferLocale(path),
|
|
12
26
|
format,
|
|
13
|
-
data:
|
|
27
|
+
data: parsed,
|
|
28
|
+
original: raw
|
|
14
29
|
};
|
|
15
30
|
}
|
|
16
31
|
export function writeLocaleFile(file) {
|
|
17
|
-
const content = file.format === "json"
|
|
18
|
-
? `${JSON.stringify(file.data, null, 2)}\n`
|
|
19
|
-
: YAML.stringify(file.data, { sortMapEntries: false });
|
|
32
|
+
const content = file.format === "json" ? toJson(file.data, file.original) : toYaml(file.data, file.original);
|
|
20
33
|
writeFileSync(file.path, content);
|
|
34
|
+
file.original = content;
|
|
21
35
|
}
|
|
22
36
|
export function inferLocale(path) {
|
|
23
37
|
const filename = path.split(/[\\/]/).at(-1) ?? "";
|
|
24
|
-
return filename.replace(/\.(json|ya?ml)$/i, "");
|
|
38
|
+
return parseLocalePath(path)?.locale ?? filename.replace(/\.(json|ya?ml)$/i, "");
|
|
39
|
+
}
|
|
40
|
+
function toJson(data, original) {
|
|
41
|
+
const indent = original?.match(/^[ \t]+(?=")/m)?.[0] ?? 2;
|
|
42
|
+
const newline = original?.includes("\r\n") ? "\r\n" : "\n";
|
|
43
|
+
const json = JSON.stringify(data, null, indent).replaceAll("\n", newline);
|
|
44
|
+
return original === undefined || original === "" || original.endsWith("\n") ? `${json}${newline}` : json;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Serializes `data` as YAML, carrying comments over from the original file by key path
|
|
48
|
+
* so that sorting or removing keys does not strip them.
|
|
49
|
+
*/
|
|
50
|
+
function toYaml(data, original) {
|
|
51
|
+
const doc = new YAML.Document(data);
|
|
52
|
+
if (original) {
|
|
53
|
+
const previous = YAML.parseDocument(original);
|
|
54
|
+
doc.comment = previous.comment;
|
|
55
|
+
doc.commentBefore = previous.commentBefore;
|
|
56
|
+
if (YAML.isMap(previous.contents) && YAML.isMap(doc.contents)) {
|
|
57
|
+
doc.commentBefore ??= takeFileHeader(previous.contents);
|
|
58
|
+
copyComments(previous.contents, doc.contents);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return doc.toString();
|
|
62
|
+
}
|
|
63
|
+
// yaml attaches a file header to the first key; split it off at the last blank line so
|
|
64
|
+
// the header stays at the top even when that key moves.
|
|
65
|
+
function takeFileHeader(map) {
|
|
66
|
+
const first = map.items[0]?.key;
|
|
67
|
+
if (!YAML.isNode(first) || !first.commentBefore?.includes("\n\n")) {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
const split = first.commentBefore.lastIndexOf("\n\n");
|
|
71
|
+
const header = first.commentBefore.slice(0, split);
|
|
72
|
+
first.commentBefore = first.commentBefore.slice(split + 2);
|
|
73
|
+
return header;
|
|
74
|
+
}
|
|
75
|
+
function copyComments(from, to) {
|
|
76
|
+
to.comment = from.comment;
|
|
77
|
+
for (const pair of to.items) {
|
|
78
|
+
const match = from.items.find((candidate) => YAML.isScalar(candidate.key) && YAML.isScalar(pair.key) && candidate.key.value === pair.key.value);
|
|
79
|
+
if (!match || !YAML.isNode(match.key) || !YAML.isNode(pair.key)) {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
pair.key.commentBefore = match.key.commentBefore;
|
|
83
|
+
pair.key.spaceBefore = match.key.spaceBefore;
|
|
84
|
+
if (YAML.isMap(match.value) && YAML.isMap(pair.value)) {
|
|
85
|
+
// A comment above a nested map's first entry is attached to the map itself; move it
|
|
86
|
+
// onto that entry's key so it follows the entry when keys are reordered.
|
|
87
|
+
const firstKey = match.value.items[0]?.key;
|
|
88
|
+
if (match.value.commentBefore && YAML.isNode(firstKey)) {
|
|
89
|
+
firstKey.commentBefore = [match.value.commentBefore, firstKey.commentBefore]
|
|
90
|
+
.filter(Boolean)
|
|
91
|
+
.join("\n");
|
|
92
|
+
match.value.commentBefore = null;
|
|
93
|
+
}
|
|
94
|
+
copyComments(match.value, pair.value);
|
|
95
|
+
}
|
|
96
|
+
else if (YAML.isNode(match.value) && YAML.isNode(pair.value)) {
|
|
97
|
+
pair.value.commentBefore = match.value.commentBefore;
|
|
98
|
+
pair.value.comment = match.value.comment;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// The first entry should never start with a blank line.
|
|
102
|
+
const first = to.items[0]?.key;
|
|
103
|
+
if (YAML.isNode(first)) {
|
|
104
|
+
first.spaceBefore = false;
|
|
105
|
+
}
|
|
25
106
|
}
|
|
26
107
|
//# sourceMappingURL=parser.js.map
|