@tolkit/cli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/dist/client.js +102 -0
- package/dist/commands/check.js +156 -0
- package/dist/commands/pull.js +95 -0
- package/dist/commands/push.js +240 -0
- package/dist/commands/scan.js +55 -0
- package/dist/commands/sync.js +78 -0
- package/dist/flatten.js +16 -0
- package/dist/glob.js +72 -0
- package/dist/index.js +84 -0
- package/dist/mcp.js +22 -0
- package/dist/meta.js +65 -0
- package/dist/plan.js +142 -0
- package/dist/plurals.js +38 -0
- package/dist/scan-config.js +87 -0
- package/dist/scan.js +200 -0
- package/package.json +36 -4
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tolkit/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
CLI and MCP server for [Tolkit](https://tolkit.app).
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
export TOLKIT_API_KEY=tlk_...
|
|
9
|
+
npx @tolkit/cli push --from messages/en.json --scan --fail-on-conflict
|
|
10
|
+
npx @tolkit/cli pull --format paraglide --out "messages/{locale}.json"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
You can also run it via the unscoped `tolkit` wrapper (`npx tolkit …`).
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { scanConfigFrom } from "./scan-config.js";
|
|
2
|
+
/** The parsed `tolkit.json` in cwd, or {} when absent/unreadable. */
|
|
3
|
+
export async function readTolkitJson() {
|
|
4
|
+
try {
|
|
5
|
+
const { readFile } = await import("node:fs/promises");
|
|
6
|
+
const v = JSON.parse(await readFile("tolkit.json", "utf8"));
|
|
7
|
+
return v && typeof v === "object" ? v : {};
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
// no tolkit.json — fine
|
|
11
|
+
return {};
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Resolve config from flags then env then a `tolkit.json` in cwd. */
|
|
15
|
+
export async function resolveConfig(flags) {
|
|
16
|
+
const fileCfg = (await readTolkitJson());
|
|
17
|
+
const url = flags.url ?? process.env.TOLKIT_URL ?? fileCfg.url ?? "http://localhost:3000";
|
|
18
|
+
const apiKey = flags.key ?? process.env.TOLKIT_API_KEY ?? fileCfg.apiKey ?? "";
|
|
19
|
+
if (!apiKey)
|
|
20
|
+
throw new Error("No API key. Set TOLKIT_API_KEY, pass --key, or add it to tolkit.json.");
|
|
21
|
+
return { url: url.replace(/\/$/, ""), apiKey, scan: scanConfigFrom(fileCfg) };
|
|
22
|
+
}
|
|
23
|
+
// Format id → file extension, where they differ (mirrors the server registry).
|
|
24
|
+
const EXT = {
|
|
25
|
+
"json-nested": "json", i18next: "json", "react-intl": "json", paraglide: "json", tolgee: "json",
|
|
26
|
+
android: "xml", "apple-strings": "strings", "apple-stringsdict": "stringsdict", "apple-xcstrings": "xcstrings", angular: "xlf",
|
|
27
|
+
};
|
|
28
|
+
/** The file extension for a format id (`i18next` → `json`, `android` → `xml`). */
|
|
29
|
+
export const extFor = (format) => EXT[format] ?? format;
|
|
30
|
+
export class TolkitClient {
|
|
31
|
+
cfg;
|
|
32
|
+
constructor(cfg) {
|
|
33
|
+
this.cfg = cfg;
|
|
34
|
+
}
|
|
35
|
+
// The user-agent only labels history entries ("cli" vs "api") server-side.
|
|
36
|
+
headers() { return { Authorization: `Bearer ${this.cfg.apiKey}`, "content-type": "application/json", "user-agent": "tolkit-cli/0.1" }; }
|
|
37
|
+
async json(path, init) {
|
|
38
|
+
const res = await fetch(`${this.cfg.url}${path}`, { ...init, headers: { ...this.headers(), ...(init?.headers ?? {}) } });
|
|
39
|
+
if (!res.ok)
|
|
40
|
+
throw new Error(`${init?.method ?? "GET"} ${path} -> ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
41
|
+
return res.json();
|
|
42
|
+
}
|
|
43
|
+
me() { return this.json("/api/v1/me"); }
|
|
44
|
+
search(projectId, q = "", limit = 500, offset = 0) {
|
|
45
|
+
return this.json(`/api/v1/${projectId}/keys?q=${encodeURIComponent(q)}&limit=${limit}&offset=${offset}`);
|
|
46
|
+
}
|
|
47
|
+
addKeys(projectId, keys) {
|
|
48
|
+
return this.json(`/api/v1/${projectId}/keys`, { method: "POST", body: JSON.stringify({ keys }) });
|
|
49
|
+
}
|
|
50
|
+
/** Replace the recorded usages of each named key (`[]` clears). */
|
|
51
|
+
putUsages(projectId, usages) {
|
|
52
|
+
return this.json(`/api/v1/${projectId}/usages`, { method: "PUT", body: JSON.stringify({ usages }) });
|
|
53
|
+
}
|
|
54
|
+
/** Every key name in the project (the API caps a page at 500). */
|
|
55
|
+
async allKeyNames(projectId) {
|
|
56
|
+
return (await this.allKeys(projectId)).map((k) => k.name);
|
|
57
|
+
}
|
|
58
|
+
/** Every project key with its per-locale values (shared-library keys are not included). */
|
|
59
|
+
async allKeys(projectId) {
|
|
60
|
+
const PAGE = 500;
|
|
61
|
+
const keys = [];
|
|
62
|
+
for (let offset = 0;; offset += PAGE) {
|
|
63
|
+
const page = (await this.search(projectId, "", PAGE, offset)).keys;
|
|
64
|
+
keys.push(...page);
|
|
65
|
+
if (page.length < PAGE)
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
return keys;
|
|
69
|
+
}
|
|
70
|
+
/** Set many values in one locale by key name (`PUT /translations`). */
|
|
71
|
+
putTranslations(projectId, body) {
|
|
72
|
+
return this.json(`/api/v1/${projectId}/translations`, { method: "PUT", body: JSON.stringify(body) });
|
|
73
|
+
}
|
|
74
|
+
/** Delete keys by name. */
|
|
75
|
+
deleteKeys(projectId, names) {
|
|
76
|
+
return this.json(`/api/v1/${projectId}/keys`, { method: "DELETE", body: JSON.stringify({ names }) });
|
|
77
|
+
}
|
|
78
|
+
/** Rename / edit one key (`PATCH /keys/:name`). */
|
|
79
|
+
patchKey(projectId, name, patch) {
|
|
80
|
+
return this.json(`/api/v1/${projectId}/keys/${encodeURIComponent(name)}`, { method: "PATCH", body: JSON.stringify(patch) });
|
|
81
|
+
}
|
|
82
|
+
/** QA issues (`GET /qa`); `severity` keeps only errors or only warnings. */
|
|
83
|
+
qa(projectId, opts = {}) {
|
|
84
|
+
const qs = new URLSearchParams();
|
|
85
|
+
if (opts.locale)
|
|
86
|
+
qs.set("locale", opts.locale);
|
|
87
|
+
if (opts.severity)
|
|
88
|
+
qs.set("severity", opts.severity);
|
|
89
|
+
const q = qs.toString();
|
|
90
|
+
return this.json(`/api/v1/${projectId}/qa${q ? `?${q}` : ""}`);
|
|
91
|
+
}
|
|
92
|
+
/** `reviewedPct` is absent on servers older than the review workflow. */
|
|
93
|
+
coverage(projectId) { return this.json(`/api/v1/${projectId}/coverage`); }
|
|
94
|
+
/** Download a locale file as text in the given format (server-serialized). */
|
|
95
|
+
async download(projectId, locale, format) {
|
|
96
|
+
const ext = extFor(format);
|
|
97
|
+
const res = await fetch(`${this.cfg.url}/api/v1/${projectId}/${locale}.${ext}?format=${encodeURIComponent(format)}`, { headers: this.headers() });
|
|
98
|
+
if (!res.ok)
|
|
99
|
+
throw new Error(`pull ${locale} -> ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
100
|
+
return res.text();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { TolkitClient } from "../client.js";
|
|
3
|
+
import { flatten } from "../flatten.js";
|
|
4
|
+
/**
|
|
5
|
+
* `--reviewed` (bare) means 100; `--reviewed=90` / `--reviewed 90` a custom
|
|
6
|
+
* bar. Returns undefined when absent; throws on a non-numeric/out-of-range value.
|
|
7
|
+
*/
|
|
8
|
+
export function parseReviewedThreshold(raw) {
|
|
9
|
+
if (raw === undefined || raw === false)
|
|
10
|
+
return undefined;
|
|
11
|
+
if (raw === true || raw === "")
|
|
12
|
+
return 100;
|
|
13
|
+
const n = Number(String(raw).replace(/%$/, ""));
|
|
14
|
+
if (!Number.isFinite(n) || n < 0 || n > 100)
|
|
15
|
+
throw new Error(`--reviewed expects a percentage 0-100, got "${raw}"`);
|
|
16
|
+
return n;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* node:util parseArgs can't express an option with an optional value, so a
|
|
20
|
+
* bare `--reviewed` (not followed by a number) is rewritten to `--reviewed=100`
|
|
21
|
+
* and a bare `--qa` (not followed by a level) to `--qa=errors`.
|
|
22
|
+
*/
|
|
23
|
+
export function normalizeArgv(argv) {
|
|
24
|
+
return argv.map((a, i) => {
|
|
25
|
+
if (a === "--reviewed" && !/^\d+(\.\d+)?%?$/.test(argv[i + 1] ?? ""))
|
|
26
|
+
return "--reviewed=100";
|
|
27
|
+
if (a === "--qa" && !/^(errors?|warnings?)$/i.test(argv[i + 1] ?? ""))
|
|
28
|
+
return "--qa=errors";
|
|
29
|
+
return a;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** `--qa` / `--qa=errors` fail on errors; `--qa=warnings` on warnings too. */
|
|
33
|
+
export function parseQaLevel(raw) {
|
|
34
|
+
if (raw === undefined || raw === false)
|
|
35
|
+
return undefined;
|
|
36
|
+
if (raw === true || raw === "")
|
|
37
|
+
return "errors";
|
|
38
|
+
const v = String(raw).toLowerCase();
|
|
39
|
+
if (v === "error" || v === "errors")
|
|
40
|
+
return "errors";
|
|
41
|
+
if (v === "warning" || v === "warnings")
|
|
42
|
+
return "warnings";
|
|
43
|
+
throw new Error(`--qa expects "errors" or "warnings", got "${raw}"`);
|
|
44
|
+
}
|
|
45
|
+
/** Does this report fail the gate? */
|
|
46
|
+
export function qaFails(report, level) {
|
|
47
|
+
return report.counts.errors > 0 || (level === "warnings" && report.counts.warnings > 0);
|
|
48
|
+
}
|
|
49
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
50
|
+
/**
|
|
51
|
+
* Human-readable QA report, grouped by locale, errors first. At most
|
|
52
|
+
* `perLocale` issues are listed per locale.
|
|
53
|
+
*/
|
|
54
|
+
export function formatQaReport(report, perLocale = 50) {
|
|
55
|
+
const { errors, warnings } = report.counts;
|
|
56
|
+
if (errors + warnings === 0)
|
|
57
|
+
return "QA: no issues";
|
|
58
|
+
const lines = [`QA: ${plural(errors, "error")}, ${plural(warnings, "warning")}`];
|
|
59
|
+
const byLocale = new Map();
|
|
60
|
+
for (const i of report.issues) {
|
|
61
|
+
const list = byLocale.get(i.locale) ?? [];
|
|
62
|
+
list.push(i);
|
|
63
|
+
byLocale.set(i.locale, list);
|
|
64
|
+
}
|
|
65
|
+
for (const [locale, list] of [...byLocale].sort(([a], [b]) => a.localeCompare(b))) {
|
|
66
|
+
const c = report.counts.byLocale[locale] ?? {
|
|
67
|
+
errors: list.filter((i) => i.severity === "error").length,
|
|
68
|
+
warnings: list.filter((i) => i.severity === "warning").length,
|
|
69
|
+
};
|
|
70
|
+
lines.push("", `${locale} (${plural(c.errors, "error")}, ${plural(c.warnings, "warning")})`);
|
|
71
|
+
const sorted = [...list].sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1));
|
|
72
|
+
const width = Math.min(40, Math.max(...sorted.slice(0, perLocale).map((i) => i.key.length)));
|
|
73
|
+
for (const i of sorted.slice(0, perLocale)) {
|
|
74
|
+
lines.push(` ${i.severity === "error" ? "error" : "warn "} ${i.key.padEnd(width)} ${i.message} [${i.code}]`);
|
|
75
|
+
}
|
|
76
|
+
if (sorted.length > perLocale)
|
|
77
|
+
lines.push(` ...and ${sorted.length - perLocale} more`);
|
|
78
|
+
}
|
|
79
|
+
return lines.join("\n");
|
|
80
|
+
}
|
|
81
|
+
/** Locales whose reviewed share is under `threshold` (the source locale never is). */
|
|
82
|
+
export function belowReviewed(coverage, threshold) {
|
|
83
|
+
return coverage.filter((c) => (c.reviewedPct ?? 0) < threshold);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Compare local source keys (--from file.json) against the server.
|
|
87
|
+
* Returns 1 if any local key is missing on the server. With --complete, also
|
|
88
|
+
* returns 1 if any target locale is below 100% coverage; with --reviewed[=N],
|
|
89
|
+
* if any locale is below N% (default 100) reviewed; with --qa[=errors], if any
|
|
90
|
+
* translation has a QA error (--qa=warnings: or a warning). 0 otherwise.
|
|
91
|
+
* `--from` may be omitted when a server-side gate is given.
|
|
92
|
+
*/
|
|
93
|
+
export async function check(cfg, opts) {
|
|
94
|
+
const reviewedBar = parseReviewedThreshold(opts.reviewed);
|
|
95
|
+
const qaLevel = parseQaLevel(opts.qa);
|
|
96
|
+
if (!opts.from && !opts.complete && reviewedBar === undefined && !qaLevel) {
|
|
97
|
+
throw new Error("check requires --from <file.json> (or a server-side gate: --complete, --reviewed, --qa)");
|
|
98
|
+
}
|
|
99
|
+
const local = opts.from ? Object.keys(flatten(JSON.parse(await readFile(opts.from, "utf8")))) : [];
|
|
100
|
+
const client = new TolkitClient(cfg);
|
|
101
|
+
const me = await client.me();
|
|
102
|
+
// Every server key, paged, so a large project never yields false "missing" reports.
|
|
103
|
+
const server = new Set(opts.from ? await client.allKeyNames(me.projectId) : []);
|
|
104
|
+
const missing = local.filter((k) => !server.has(k));
|
|
105
|
+
let bad = false;
|
|
106
|
+
if (missing.length) {
|
|
107
|
+
bad = true;
|
|
108
|
+
console.error(`Missing ${missing.length} key(s) on the server:`);
|
|
109
|
+
for (const k of missing.slice(0, 50))
|
|
110
|
+
console.error(` - ${k}`);
|
|
111
|
+
if (missing.length > 50)
|
|
112
|
+
console.error(` ...and ${missing.length - 50} more`);
|
|
113
|
+
}
|
|
114
|
+
const cov = opts.complete || reviewedBar !== undefined ? (await client.coverage(me.projectId)).coverage : [];
|
|
115
|
+
if (opts.complete) {
|
|
116
|
+
const incomplete = cov.filter((c) => c.pct < 100);
|
|
117
|
+
if (incomplete.length) {
|
|
118
|
+
bad = true;
|
|
119
|
+
console.error(`Incomplete locales: ${incomplete.map((c) => `${c.locale} (${c.pct}%)`).join(", ")}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (reviewedBar !== undefined) {
|
|
123
|
+
if (cov.some((c) => c.reviewedPct === undefined)) {
|
|
124
|
+
bad = true;
|
|
125
|
+
console.error("The server does not report review coverage; upgrade Tolkit to use --reviewed.");
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
const under = belowReviewed(cov, reviewedBar);
|
|
129
|
+
if (under.length) {
|
|
130
|
+
bad = true;
|
|
131
|
+
console.error(`Below ${reviewedBar}% reviewed: ${under.map((c) => `${c.locale} (${c.reviewedPct}%${c.outdated ? `, ${c.outdated} outdated` : ""})`).join(", ")}`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (qaLevel) {
|
|
136
|
+
const report = await client.qa(me.projectId);
|
|
137
|
+
if (qaFails(report, qaLevel)) {
|
|
138
|
+
bad = true;
|
|
139
|
+
console.error(formatQaReport(report));
|
|
140
|
+
}
|
|
141
|
+
else if (report.counts.warnings > 0) {
|
|
142
|
+
// warnings don't fail the default gate, but are worth seeing
|
|
143
|
+
console.log(formatQaReport(report));
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (!bad) {
|
|
147
|
+
const passed = [
|
|
148
|
+
...(opts.from ? [`${local.length} local keys present`] : []),
|
|
149
|
+
...(opts.complete ? ["all locales complete"] : []),
|
|
150
|
+
...(reviewedBar !== undefined ? [`all locales >= ${reviewedBar}% reviewed`] : []),
|
|
151
|
+
...(qaLevel ? [qaLevel === "warnings" ? "no QA issues" : "no QA errors"] : []),
|
|
152
|
+
];
|
|
153
|
+
console.log(`check passed: ${passed.join(", ")}`);
|
|
154
|
+
}
|
|
155
|
+
return bad ? 1 : 0;
|
|
156
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { TolkitClient, extFor } from "../client.js";
|
|
4
|
+
import { flatten } from "../flatten.js";
|
|
5
|
+
import { isLocalePattern, localePattern, parseLocaleList, planPush } from "../plan.js";
|
|
6
|
+
/**
|
|
7
|
+
* Patch only the specified keys inside a JSON object, preserving original key
|
|
8
|
+
* order, `$schema`, indentation, and trailing newline. Supports both flat keys
|
|
9
|
+
* (`"a.b"` or `"a_b"`) and nested JSON objects.
|
|
10
|
+
*/
|
|
11
|
+
export function patchJsonInPlace(raw, updates) {
|
|
12
|
+
const obj = JSON.parse(raw);
|
|
13
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
14
|
+
throw new Error("Source file must be a JSON object");
|
|
15
|
+
}
|
|
16
|
+
const indent = raw.match(/^(\t+| +)"/m)?.[1] ?? " ";
|
|
17
|
+
const eol = raw.endsWith("\n") ? "\n" : "";
|
|
18
|
+
let updated = 0;
|
|
19
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
20
|
+
if (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "string") {
|
|
21
|
+
if (obj[key] !== value) {
|
|
22
|
+
obj[key] = value;
|
|
23
|
+
updated++;
|
|
24
|
+
}
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
// Nested object fallback (dot-separated path)
|
|
28
|
+
const parts = key.split(".");
|
|
29
|
+
let cur = obj;
|
|
30
|
+
let ok = true;
|
|
31
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
32
|
+
const next = cur[parts[i]];
|
|
33
|
+
if (!next || typeof next !== "object" || Array.isArray(next)) {
|
|
34
|
+
ok = false;
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
cur = next;
|
|
38
|
+
}
|
|
39
|
+
const leaf = parts[parts.length - 1];
|
|
40
|
+
if (ok && Object.prototype.hasOwnProperty.call(cur, leaf) && typeof cur[leaf] === "string" && cur[leaf] !== value) {
|
|
41
|
+
cur[leaf] = value;
|
|
42
|
+
updated++;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return { text: `${JSON.stringify(obj, null, indent)}${eol}`, updated };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Download target locale files. By default skips `sourceLocale` (pass
|
|
49
|
+
* `--locale <code >` or `--locales a,b` to choose explicitly). Pass `--source <file>`
|
|
50
|
+
* to patch Tolkit-only source edits in-place in the existing source JSON file
|
|
51
|
+
* without reordering keys or reverting git-side changes.
|
|
52
|
+
*/
|
|
53
|
+
export async function pull(cfg, opts, client = new TolkitClient(cfg)) {
|
|
54
|
+
const me = await client.me();
|
|
55
|
+
const format = opts.format ?? "json";
|
|
56
|
+
const out = opts.out ?? ".";
|
|
57
|
+
const requested = opts.locale ? [opts.locale] : parseLocaleList(opts.locales);
|
|
58
|
+
const codes = requested ?? me.locales.map((l) => l.code).filter((c) => c !== me.sourceLocale);
|
|
59
|
+
const unique = [...new Set(codes)];
|
|
60
|
+
const ext = extFor(format);
|
|
61
|
+
const pattern = isLocalePattern(out) ? localePattern(out) : null;
|
|
62
|
+
for (const code of unique) {
|
|
63
|
+
const text = await client.download(me.projectId, code, format);
|
|
64
|
+
const file = pattern ? pattern.split("{locale}").join(code) : join(out, `${code}.${ext}`);
|
|
65
|
+
await mkdir(dirname(file), { recursive: true });
|
|
66
|
+
await writeFile(file, text, "utf8");
|
|
67
|
+
console.log(`pulled ${file}`);
|
|
68
|
+
}
|
|
69
|
+
if (opts.source) {
|
|
70
|
+
const raw = await readFile(opts.source, "utf8");
|
|
71
|
+
const local = flatten(JSON.parse(raw));
|
|
72
|
+
delete local.$schema;
|
|
73
|
+
const serverKeys = await client.allKeys(me.projectId);
|
|
74
|
+
const serverByName = new Map(serverKeys.map((k) => [k.name, k.values[me.sourceLocale]?.value ?? ""]));
|
|
75
|
+
const plan = planPush(local, serverKeys.map((k) => ({ name: k.name, source: k.values[me.sourceLocale]?.value, synced: k.sourceSynced })));
|
|
76
|
+
if (plan.edited.length === 0) {
|
|
77
|
+
console.log(`source ${opts.source}: up to date`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const updates = {};
|
|
81
|
+
for (const name of plan.edited) {
|
|
82
|
+
const value = serverByName.get(name);
|
|
83
|
+
if (value !== undefined)
|
|
84
|
+
updates[name] = value;
|
|
85
|
+
}
|
|
86
|
+
const { text, updated } = patchJsonInPlace(raw, updates);
|
|
87
|
+
if (updated > 0) {
|
|
88
|
+
await writeFile(opts.source, text, "utf8");
|
|
89
|
+
console.log(`patched ${opts.source}: ${updated} source edit(s) from Tolkit`);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
console.log(`source ${opts.source}: up to date`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { createInterface } from "node:readline/promises";
|
|
3
|
+
import { TolkitClient } from "../client.js";
|
|
4
|
+
import { flatten } from "../flatten.js";
|
|
5
|
+
import { loadMeta, metaPathFor } from "../meta.js";
|
|
6
|
+
import { groupI18nextPlurals } from "../plurals.js";
|
|
7
|
+
import { formatList, formatPushPlan, formatSourceConflicts, formatTranslationPlan, parseLocaleList, planPush, planTranslations, resolveLocaleFiles, } from "../plan.js";
|
|
8
|
+
import { scan } from "./scan.js";
|
|
9
|
+
// The keys endpoint accepts at most 1000 keys per request.
|
|
10
|
+
const CHUNK = 1000;
|
|
11
|
+
// PUT /translations and DELETE /keys take up to 10000 / 5000 names.
|
|
12
|
+
const WRITE_CHUNK = 5000;
|
|
13
|
+
/** Read a JSON locale file → flat dot-keys (i18next suffix groups → ICU plurals with --plurals i18next). */
|
|
14
|
+
async function readFlat(path, plurals) {
|
|
15
|
+
let raw;
|
|
16
|
+
try {
|
|
17
|
+
raw = JSON.parse(await readFile(path, "utf8"));
|
|
18
|
+
}
|
|
19
|
+
catch (e) {
|
|
20
|
+
throw new Error(`Could not read ${path}: ${e instanceof Error ? e.message : e}`);
|
|
21
|
+
}
|
|
22
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
23
|
+
throw new Error(`${path} must contain a JSON object`);
|
|
24
|
+
// `$schema` (inlang's message format starts every file with one) is not a message.
|
|
25
|
+
const { $schema: _schema, ...messages } = raw;
|
|
26
|
+
const flat = flatten(messages);
|
|
27
|
+
return plurals === "i18next" ? groupI18nextPlurals(flat) : flat;
|
|
28
|
+
}
|
|
29
|
+
/** Why `sync` stopped: these local values differ from the server, and pulling would overwrite them. */
|
|
30
|
+
export function conflictRefusal(names) {
|
|
31
|
+
return [
|
|
32
|
+
`sync: ${names.length} local value(s) differ from the server; nothing was written.`,
|
|
33
|
+
formatList("differs", names),
|
|
34
|
+
"Pass --update to push your local values, or --force to discard them and take the server's.",
|
|
35
|
+
].join("\n");
|
|
36
|
+
}
|
|
37
|
+
async function exists(path) {
|
|
38
|
+
try {
|
|
39
|
+
await readFile(path);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function confirmDelete(count) {
|
|
47
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
48
|
+
try {
|
|
49
|
+
const answer = await rl.question(`Delete ${count} key(s) (and all their translations) from the server? [y/N] `);
|
|
50
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
rl.close();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Upload a JSON source file and/or target-locale files.
|
|
58
|
+
*
|
|
59
|
+
* - `--from <file>`: new keys are created with their source value (plus
|
|
60
|
+
* descriptions / maxLength / plural from a sidecar `<name>.meta.json`).
|
|
61
|
+
* Existing keys are compared three ways with the text the last push sent
|
|
62
|
+
* (see `planPush`): the repo's changes are written, edits made in Tolkit are
|
|
63
|
+
* kept, and changes on both sides are conflicts that `--update` overwrites.
|
|
64
|
+
* - `--translations <pattern>` (`locales/{locale}.json`, `locales/*.json` or a
|
|
65
|
+
* directory) pushes target-locale files: empty server cells are filled,
|
|
66
|
+
* differing values are only overwritten with `--update`. Keys must already
|
|
67
|
+
* exist (or be created by this push's `--from`); others are reported.
|
|
68
|
+
* `--locales a,b` limits the locales.
|
|
69
|
+
* - `--remove-missing` deletes server keys absent from `--from` (asks first on
|
|
70
|
+
* a TTY; `--yes` to skip; refuses otherwise). Shared-library keys are not
|
|
71
|
+
* project keys and are never deleted.
|
|
72
|
+
* - `--dry-run` prints the plan and writes nothing.
|
|
73
|
+
* - `--scan` follows up with `tolkit scan`.
|
|
74
|
+
*/
|
|
75
|
+
export async function push(cfg, opts, client = new TolkitClient(cfg)) {
|
|
76
|
+
if (!opts.from && !opts.translations)
|
|
77
|
+
throw new Error("push requires --from <file.json> and/or --translations <pattern>");
|
|
78
|
+
if (opts.plurals && opts.plurals !== "i18next" && opts.plurals !== "icu") {
|
|
79
|
+
throw new Error(`--plurals must be "i18next" or "icu" (got "${opts.plurals}")`);
|
|
80
|
+
}
|
|
81
|
+
if (opts["remove-missing"] && !opts.from)
|
|
82
|
+
throw new Error("--remove-missing needs --from <file.json> (the complete source file)");
|
|
83
|
+
const dryRun = !!opts["dry-run"];
|
|
84
|
+
const me = await client.me();
|
|
85
|
+
const server = await client.allKeys(me.projectId);
|
|
86
|
+
const serverNames = new Set(server.map((k) => k.name));
|
|
87
|
+
// ---- source file ----
|
|
88
|
+
let flat = {};
|
|
89
|
+
let keys = [];
|
|
90
|
+
let plan = null;
|
|
91
|
+
let sidecar = null;
|
|
92
|
+
if (opts.from) {
|
|
93
|
+
flat = await readFlat(opts.from, opts.plurals);
|
|
94
|
+
sidecar = await loadMeta(opts.from);
|
|
95
|
+
keys = Object.entries(flat).map(([key, source]) => {
|
|
96
|
+
const meta = sidecar?.meta[key];
|
|
97
|
+
return {
|
|
98
|
+
key,
|
|
99
|
+
source,
|
|
100
|
+
...(meta?.description ? { description: meta.description } : {}),
|
|
101
|
+
...(meta?.maxLength ? { maxLength: meta.maxLength } : {}),
|
|
102
|
+
...(meta?.plural !== undefined ? { isPlural: meta.plural } : {}),
|
|
103
|
+
...(meta?.pluralArg ? { pluralArg: meta.pluralArg } : {}),
|
|
104
|
+
...(meta?.role ? { role: meta.role } : {}),
|
|
105
|
+
};
|
|
106
|
+
});
|
|
107
|
+
if (keys.length === 0)
|
|
108
|
+
throw new Error(`No keys found in ${opts.from}`);
|
|
109
|
+
plan = planPush(flat, server.map((k) => ({ name: k.name, source: k.values[me.sourceLocale]?.value ?? "", synced: k.sourceSynced })), { update: opts.update, removeMissing: opts["remove-missing"] });
|
|
110
|
+
}
|
|
111
|
+
// ---- target-locale files ----
|
|
112
|
+
const translationPlans = [];
|
|
113
|
+
if (opts.translations) {
|
|
114
|
+
const targets = me.locales.map((l) => l.code).filter((c) => c !== me.sourceLocale);
|
|
115
|
+
const wanted = parseLocaleList(opts.locales);
|
|
116
|
+
const unknownLocales = (wanted ?? []).filter((c) => !targets.includes(c));
|
|
117
|
+
if (unknownLocales.length) {
|
|
118
|
+
throw new Error(`Not target locales of this project: ${unknownLocales.join(", ")} (have: ${targets.join(", ") || "none"})`);
|
|
119
|
+
}
|
|
120
|
+
// Keys this push creates count as known to the translation files.
|
|
121
|
+
const known = new Set([...serverNames, ...(plan?.create ?? [])]);
|
|
122
|
+
for (const { locale, path } of resolveLocaleFiles(opts.translations, wanted ?? targets)) {
|
|
123
|
+
if (!(await exists(path))) {
|
|
124
|
+
if (wanted)
|
|
125
|
+
console.warn(`push: ${path} not found — skipping ${locale}`);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const local = await readFlat(path, opts.plurals);
|
|
129
|
+
const serverValues = Object.fromEntries(server.map((k) => [k.name, k.values[locale]?.value ?? ""]));
|
|
130
|
+
translationPlans.push({ locale, path, plan: planTranslations(local, serverValues, { update: opts.update, serverKeys: known }) });
|
|
131
|
+
}
|
|
132
|
+
if (translationPlans.length === 0)
|
|
133
|
+
console.warn(`push: no translation files matched ${opts.translations}`);
|
|
134
|
+
}
|
|
135
|
+
const serverSources = new Map(server.map((k) => [k.name, k.values[me.sourceLocale]?.value ?? ""]));
|
|
136
|
+
const conflicts = (plan?.conflicts.length ?? 0) + translationPlans.reduce((n, t) => n + t.plan.skippedConflicts.length, 0);
|
|
137
|
+
if (dryRun) {
|
|
138
|
+
console.log("push --dry-run: nothing will be written");
|
|
139
|
+
if (plan) {
|
|
140
|
+
console.log(`keys (${opts.from}):\n${formatPushPlan(plan, { update: opts.update })}`);
|
|
141
|
+
if (plan.conflicts.length)
|
|
142
|
+
console.log(formatSourceConflicts(plan.conflicts, flat, serverSources));
|
|
143
|
+
}
|
|
144
|
+
for (const t of translationPlans)
|
|
145
|
+
console.log(formatTranslationPlan(t.locale, t.path, t.plan));
|
|
146
|
+
return { aborted: false, conflicts };
|
|
147
|
+
}
|
|
148
|
+
if (opts.refuseConflicts && conflicts > 0 && !opts.update) {
|
|
149
|
+
const names = [...(plan?.conflicts ?? []), ...translationPlans.flatMap((t) => t.plan.skippedConflicts.map((n) => `${n} (${t.locale})`))];
|
|
150
|
+
throw new Error(conflictRefusal(names));
|
|
151
|
+
}
|
|
152
|
+
if (plan && plan.remove.length > 0 && !opts.yes) {
|
|
153
|
+
if (!process.stdin.isTTY) {
|
|
154
|
+
throw new Error(`--remove-missing would delete ${plan.remove.length} key(s); re-run with --yes to confirm (or --dry-run to review)\n${formatList("delete", plan.remove)}`);
|
|
155
|
+
}
|
|
156
|
+
console.log(formatList("delete", plan.remove));
|
|
157
|
+
if (!(await confirmDelete(plan.remove.length))) {
|
|
158
|
+
console.log("push: aborted, nothing written");
|
|
159
|
+
return { aborted: true, conflicts };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// ---- writes ----
|
|
163
|
+
if (opts.from && plan) {
|
|
164
|
+
let created = 0;
|
|
165
|
+
let skipped = 0;
|
|
166
|
+
let described = 0;
|
|
167
|
+
let limited = 0;
|
|
168
|
+
let roled = 0;
|
|
169
|
+
for (let i = 0; i < keys.length; i += CHUNK) {
|
|
170
|
+
const res = await client.addKeys(me.projectId, keys.slice(i, i + CHUNK));
|
|
171
|
+
created += res.created.length;
|
|
172
|
+
skipped += res.skipped;
|
|
173
|
+
described += res.descriptionsUpdated ?? 0;
|
|
174
|
+
limited += res.maxLengthsUpdated ?? 0;
|
|
175
|
+
roled += res.rolesUpdated ?? 0;
|
|
176
|
+
}
|
|
177
|
+
let updated = 0;
|
|
178
|
+
// Acknowledged values are unchanged, so the server only records them as pushed.
|
|
179
|
+
const sends = [...plan.update, ...plan.ack];
|
|
180
|
+
for (let i = 0; i < sends.length; i += WRITE_CHUNK) {
|
|
181
|
+
const names = sends.slice(i, i + WRITE_CHUNK);
|
|
182
|
+
const res = await client.putTranslations(me.projectId, {
|
|
183
|
+
locale: me.sourceLocale,
|
|
184
|
+
values: Object.fromEntries(names.map((n) => [n, flat[n]])),
|
|
185
|
+
});
|
|
186
|
+
updated += res.updated;
|
|
187
|
+
}
|
|
188
|
+
const withDesc = keys.filter((k) => k.description).length;
|
|
189
|
+
const withMax = keys.filter((k) => k.maxLength).length;
|
|
190
|
+
const withRole = keys.filter((k) => k.role).length;
|
|
191
|
+
console.log(`pushed ${opts.from}: ${created} created, ${skipped} existing` +
|
|
192
|
+
(updated ? `, ${updated} source value(s) updated` : "") +
|
|
193
|
+
(plan.conflicts.length ? `, ${plan.conflicts.length} changed on both sides (use --update to overwrite)` : "") +
|
|
194
|
+
(plan.edited.length ? `, ${plan.edited.length} edited in Tolkit (kept; pull to bring them in)` : "") +
|
|
195
|
+
(sidecar
|
|
196
|
+
? ` · ${withDesc} description(s)` +
|
|
197
|
+
(withMax ? `, ${withMax} max length(s)` : "") +
|
|
198
|
+
(withRole ? `, ${withRole} role(s)` : "") +
|
|
199
|
+
` from ${sidecar.path}` +
|
|
200
|
+
(described || limited || roled
|
|
201
|
+
? ` (${described} description(s), ${limited} max length(s), ${roled} role(s) updated)`
|
|
202
|
+
: "")
|
|
203
|
+
: ""));
|
|
204
|
+
if (plan.conflicts.length) {
|
|
205
|
+
console.log(formatSourceConflicts(plan.conflicts, flat, serverSources));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
for (const t of translationPlans) {
|
|
209
|
+
const names = Object.keys(t.plan.values);
|
|
210
|
+
let updated = 0;
|
|
211
|
+
const unknown = new Set(t.plan.unknown);
|
|
212
|
+
for (let i = 0; i < names.length; i += WRITE_CHUNK) {
|
|
213
|
+
const part = names.slice(i, i + WRITE_CHUNK);
|
|
214
|
+
const res = await client.putTranslations(me.projectId, {
|
|
215
|
+
locale: t.locale,
|
|
216
|
+
values: Object.fromEntries(part.map((n) => [n, t.plan.values[n]])),
|
|
217
|
+
createMissingKeys: false,
|
|
218
|
+
});
|
|
219
|
+
updated += res.updated;
|
|
220
|
+
for (const u of res.unknownKeys)
|
|
221
|
+
unknown.add(u);
|
|
222
|
+
}
|
|
223
|
+
console.log(`pushed ${t.path} → ${t.locale}: ${updated} updated (${t.plan.filled.length} filled, ${t.plan.overwritten.length} overwritten), ${t.plan.unchanged} unchanged` +
|
|
224
|
+
(t.plan.skippedConflicts.length ? `, ${t.plan.skippedConflicts.length} differ (use --update to overwrite)` : "") +
|
|
225
|
+
(unknown.size ? `, ${unknown.size} unknown key(s) ignored: ${[...unknown].slice(0, 10).join(", ")}${unknown.size > 10 ? ", …" : ""}` : ""));
|
|
226
|
+
}
|
|
227
|
+
if (plan && plan.remove.length > 0) {
|
|
228
|
+
let deleted = 0;
|
|
229
|
+
for (let i = 0; i < plan.remove.length; i += WRITE_CHUNK) {
|
|
230
|
+
deleted += (await client.deleteKeys(me.projectId, plan.remove.slice(i, i + WRITE_CHUNK))).deleted;
|
|
231
|
+
}
|
|
232
|
+
console.log(`removed ${deleted} key(s) missing from ${opts.from}`);
|
|
233
|
+
}
|
|
234
|
+
if (opts.scan) {
|
|
235
|
+
// The pushed file and its sidecar contain every key name; never count them.
|
|
236
|
+
const exclude = opts.from ? [opts.from, metaPathFor(opts.from)] : [];
|
|
237
|
+
await scan(cfg, { root: opts.root, exclude }, client);
|
|
238
|
+
}
|
|
239
|
+
return { aborted: false, conflicts };
|
|
240
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { relative, resolve } from "node:path";
|
|
2
|
+
import { TolkitClient } from "../client.js";
|
|
3
|
+
import { compileScanConfig, walkFiles } from "../scan-config.js";
|
|
4
|
+
import { createCollector, looksBinary, USAGES_PER_KEY_MAX } from "../scan.js";
|
|
5
|
+
// Keys per PUT — keeps each request well under any body limit even when every
|
|
6
|
+
// key carries the full 20 usages.
|
|
7
|
+
const CHUNK = 250;
|
|
8
|
+
/**
|
|
9
|
+
* Find where each of the project's keys is used in the source tree and upload
|
|
10
|
+
* the result (replace-per-scan: every project key is sent, `[]` for keys found
|
|
11
|
+
* nowhere, so stale locations are cleared). `--dry-run` prints instead.
|
|
12
|
+
*/
|
|
13
|
+
export async function scan(cfg, opts, client = new TolkitClient(cfg)) {
|
|
14
|
+
const root = resolve(opts.root ?? ".");
|
|
15
|
+
const me = await client.me();
|
|
16
|
+
const keys = await client.allKeyNames(me.projectId);
|
|
17
|
+
if (keys.length === 0) {
|
|
18
|
+
console.log("scan: the project has no keys yet — nothing to look for");
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
// Extra excludes (e.g. push --scan's own source file) are root-relative.
|
|
22
|
+
const extra = (opts.exclude ?? []).map((p) => relative(root, resolve(p)).replace(/\\/g, "/"));
|
|
23
|
+
const rules = compileScanConfig(cfg.scan, extra);
|
|
24
|
+
const collector = createCollector(keys, cfg.scan.prefixes);
|
|
25
|
+
let files = 0;
|
|
26
|
+
for await (const f of walkFiles(root, rules, (m) => console.warn(`scan: ${m}`), looksBinary)) {
|
|
27
|
+
collector.addFile(f.path, f.text);
|
|
28
|
+
files++;
|
|
29
|
+
}
|
|
30
|
+
const res = collector.result();
|
|
31
|
+
console.log(`scan: ${files} file(s), ${res.found}/${keys.length} key(s) found, ${res.hits} usage(s)`);
|
|
32
|
+
if (res.capped.length) {
|
|
33
|
+
console.log(`scan: ${res.capped.length} key(s) used more than ${USAGES_PER_KEY_MAX} times; kept the first ${USAGES_PER_KEY_MAX}:`);
|
|
34
|
+
for (const c of res.capped.slice(0, 10))
|
|
35
|
+
console.log(` ${c.key} (${c.total} usages)`);
|
|
36
|
+
if (res.capped.length > 10)
|
|
37
|
+
console.log(` ...and ${res.capped.length - 10} more`);
|
|
38
|
+
}
|
|
39
|
+
if (opts["dry-run"]) {
|
|
40
|
+
for (const [key, list] of Object.entries(res.usages)) {
|
|
41
|
+
for (const u of list)
|
|
42
|
+
console.log(`${key}\t${u.file}:${u.line}\t${u.element ?? "-"}\t${u.snippet}`);
|
|
43
|
+
}
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const entries = Object.entries(res.usages);
|
|
47
|
+
let stored = 0;
|
|
48
|
+
let ignored = 0;
|
|
49
|
+
for (let i = 0; i < entries.length; i += CHUNK) {
|
|
50
|
+
const r = await client.putUsages(me.projectId, Object.fromEntries(entries.slice(i, i + CHUNK)));
|
|
51
|
+
stored += r.usages;
|
|
52
|
+
ignored += r.ignored;
|
|
53
|
+
}
|
|
54
|
+
console.log(`scan: uploaded ${stored} usage(s)` + (ignored ? ` · ${ignored} key(s) no longer in the project` : ""));
|
|
55
|
+
}
|