ext-localize 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.
@@ -0,0 +1,48 @@
1
+ import { fetchJson, withRetry } from "../retry.js";
2
+ import { RESPONSE_SCHEMA, buildUserPrompt, systemPromptFor, parseTranslations } from "./prompt.js";
3
+ import { OutputTruncatedError, ProviderError } from "./types.js";
4
+ function normalizeHost(host) {
5
+ const withScheme = /^https?:\/\//.test(host) ? host : `http://${host}`;
6
+ return withScheme.replace(/\/+$/, "");
7
+ }
8
+ /**
9
+ * A local model through Ollama's /api/chat with a JSON schema "format".
10
+ * Nothing leaves your machine. Smaller batches, because small local models
11
+ * lose track of long lists. There is no default model: pass --model.
12
+ */
13
+ export class OllamaProvider {
14
+ name = "ollama";
15
+ label;
16
+ limits = { maxItems: 15, maxChars: 3000 };
17
+ model;
18
+ host;
19
+ constructor(opts) {
20
+ this.model = opts.model;
21
+ this.host = normalizeHost(opts.host ?? process.env.OLLAMA_HOST ?? "http://localhost:11434");
22
+ this.label = `ollama/${this.model}`;
23
+ }
24
+ async translateBatch(req) {
25
+ const body = {
26
+ model: this.model,
27
+ stream: false,
28
+ format: RESPONSE_SCHEMA,
29
+ options: { temperature: 0 },
30
+ messages: [
31
+ { role: "system", content: systemPromptFor(req.kind) },
32
+ { role: "user", content: buildUserPrompt(req) },
33
+ ],
34
+ };
35
+ let data;
36
+ try {
37
+ data = (await withRetry(() => fetchJson(`${this.host}/api/chat`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }), { retries: 2 }));
38
+ }
39
+ catch (e) {
40
+ if (e instanceof TypeError)
41
+ throw new ProviderError(`cannot reach Ollama at ${this.host}. Is "ollama serve" running?`);
42
+ throw e;
43
+ }
44
+ if (data.done_reason === "length")
45
+ throw new OutputTruncatedError();
46
+ return parseTranslations(data.message?.content ?? "", req);
47
+ }
48
+ }
@@ -0,0 +1,50 @@
1
+ import { fetchJson, withRetry } from "../retry.js";
2
+ import { RESPONSE_SCHEMA, buildUserPrompt, systemPromptFor, parseTranslations } from "./prompt.js";
3
+ import { LLM_LIMITS, OutputTruncatedError, ProviderError } from "./types.js";
4
+ /**
5
+ * OpenAI Chat Completions with a strict JSON schema response format.
6
+ * Also works with OpenAI-compatible local servers (LM Studio, vLLM, llama.cpp)
7
+ * through OPENAI_BASE_URL. There is no default model: pass --model.
8
+ */
9
+ export class OpenAIProvider {
10
+ name = "openai";
11
+ label;
12
+ limits = LLM_LIMITS;
13
+ model;
14
+ baseUrl;
15
+ apiKey;
16
+ constructor(opts) {
17
+ this.model = opts.model;
18
+ this.baseUrl = (opts.baseUrl ?? process.env.OPENAI_BASE_URL ?? "https://api.openai.com/v1").replace(/\/+$/, "");
19
+ this.apiKey = opts.apiKey ?? process.env.OPENAI_API_KEY;
20
+ if (!this.apiKey && this.baseUrl.includes("api.openai.com")) {
21
+ throw new ProviderError("OPENAI_API_KEY is not set");
22
+ }
23
+ this.label = `openai/${this.model}`;
24
+ }
25
+ async translateBatch(req) {
26
+ const headers = { "content-type": "application/json" };
27
+ if (this.apiKey)
28
+ headers.authorization = `Bearer ${this.apiKey}`;
29
+ const body = {
30
+ model: this.model,
31
+ messages: [
32
+ { role: "system", content: systemPromptFor(req.kind) },
33
+ { role: "user", content: buildUserPrompt(req) },
34
+ ],
35
+ response_format: {
36
+ type: "json_schema",
37
+ json_schema: { name: "translations", strict: true, schema: RESPONSE_SCHEMA },
38
+ },
39
+ };
40
+ const data = (await withRetry(() => fetchJson(`${this.baseUrl}/chat/completions`, { method: "POST", headers, body: JSON.stringify(body) })));
41
+ const choice = data.choices?.[0];
42
+ if (!choice?.message)
43
+ throw new ProviderError("response has no choices");
44
+ if (choice.message.refusal)
45
+ throw new ProviderError(`model refused: ${choice.message.refusal}`);
46
+ if (choice.finish_reason === "length")
47
+ throw new OutputTruncatedError();
48
+ return parseTranslations(choice.message.content ?? "", req);
49
+ }
50
+ }
@@ -0,0 +1,100 @@
1
+ import { localeDisplayName } from "../locales.js";
2
+ import { ProviderError } from "./types.js";
3
+ /**
4
+ * Shared prompt for LLM providers (Anthropic, OpenAI, Ollama).
5
+ * The system prompt is constant so providers can cache it.
6
+ */
7
+ export const SYSTEM_PROMPT = `You translate user interface strings of a Chrome browser extension.
8
+
9
+ Rules:
10
+ 1. Markers like <x id="0"/> stand for placeholders that the extension fills in at runtime. Copy every marker exactly once, unchanged, at the natural position for the target language.
11
+ 2. Markers like <x id="1">Name</x> wrap words that must not be translated. Copy them exactly, including the inner text.
12
+ 3. Never add, remove, merge or rename markers.
13
+ 4. Keep the meaning and tone. UI text must stay short: aim for a length close to the source.
14
+ 5. The description and marker notes are context for you. Do not translate or include them.
15
+ 6. Keep leading and trailing spaces, line breaks and punctuation style that the target language allows.
16
+ 7. When a glossary is given, always use its translations for those terms.
17
+ 8. Return one entry for every input key, with the key unchanged.`;
18
+ /** Instructions for store listing text (name, summary, long description). */
19
+ export const LISTING_SYSTEM_PROMPT = `You translate the store listing of a browser extension (Chrome Web Store, Firefox Add-ons, Edge Add-ons).
20
+
21
+ Rules:
22
+ 1. Markers like <x id="1">Name</x> wrap words that must not be translated. Copy them exactly, including the inner text. Never add, remove or rename markers.
23
+ 2. Write natural, fluent marketing text for the target language. Keep the meaning; do not add claims or keywords that are not in the source.
24
+ 3. Keep the structure of the long description: the same paragraphs, line breaks, list markers ("- ", "* ", "1. ") and blank lines.
25
+ 4. Respect the maximum length given in the description of each string.
26
+ 5. The description of each string is context for you. Do not translate or include it.
27
+ 6. When a glossary is given, always use its translations for those terms.
28
+ 7. Return one entry for every input key, with the key unchanged.`;
29
+ export function systemPromptFor(kind) {
30
+ return kind === "listing" ? LISTING_SYSTEM_PROMPT : SYSTEM_PROMPT;
31
+ }
32
+ /** JSON schema for the structured response: an array, since keys are dynamic. */
33
+ export const RESPONSE_SCHEMA = {
34
+ type: "object",
35
+ properties: {
36
+ translations: {
37
+ type: "array",
38
+ items: {
39
+ type: "object",
40
+ properties: {
41
+ key: { type: "string" },
42
+ text: { type: "string" },
43
+ },
44
+ required: ["key", "text"],
45
+ additionalProperties: false,
46
+ },
47
+ },
48
+ },
49
+ required: ["translations"],
50
+ additionalProperties: false,
51
+ };
52
+ export function buildUserPrompt(req) {
53
+ const lines = [];
54
+ lines.push(`Source language: ${localeDisplayName(req.sourceLocale)} (${req.sourceLocale})`);
55
+ lines.push(`Target language: ${localeDisplayName(req.targetLocale)} (${req.targetLocale})`);
56
+ if (req.formality === "more" || req.formality === "prefer_more") {
57
+ lines.push("Tone: formal. Use the formal form of address where the language has one (for example German \"Sie\", French \"vous\").");
58
+ }
59
+ else if (req.formality === "less" || req.formality === "prefer_less") {
60
+ lines.push("Tone: informal. Use the informal form of address where the language has one (for example German \"du\", French \"tu\").");
61
+ }
62
+ if (req.terms.length) {
63
+ lines.push("", "Glossary (always use these translations):");
64
+ for (const [term, translation] of req.terms)
65
+ lines.push(`- "${term}" -> "${translation}"`);
66
+ }
67
+ const items = req.items.map((i) => {
68
+ const o = { key: i.key, text: i.text };
69
+ if (i.description)
70
+ o.description = i.description;
71
+ if (i.markerHints?.length)
72
+ o.markers = i.markerHints;
73
+ return o;
74
+ });
75
+ lines.push("", "Strings to translate (JSON):", JSON.stringify(items, null, 1));
76
+ lines.push("", `Return {"translations": [{"key": ..., "text": ...}]} with ${req.items.length} entries.`);
77
+ return lines.join("\n");
78
+ }
79
+ /** Parse the model's JSON answer into key -> text. Unknown keys are ignored. */
80
+ export function parseTranslations(raw, req) {
81
+ let data;
82
+ const trimmed = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
83
+ try {
84
+ data = JSON.parse(trimmed);
85
+ }
86
+ catch {
87
+ throw new ProviderError(`model did not return valid JSON: ${raw.slice(0, 200)}`);
88
+ }
89
+ const list = data?.translations;
90
+ if (!Array.isArray(list))
91
+ throw new ProviderError(`model JSON has no "translations" array`);
92
+ const wanted = new Set(req.items.map((i) => i.key));
93
+ const out = {};
94
+ for (const entry of list) {
95
+ const e = entry;
96
+ if (typeof e?.key === "string" && typeof e.text === "string" && wanted.has(e.key))
97
+ out[e.key] = e.text;
98
+ }
99
+ return out;
100
+ }
@@ -0,0 +1,18 @@
1
+ /** DeepL's formality values. LLM providers get them as a tone instruction. */
2
+ export const FORMALITIES = ["default", "more", "less", "prefer_more", "prefer_less"];
3
+ /** The response was cut off (output token limit). The caller splits the batch. */
4
+ export class OutputTruncatedError extends Error {
5
+ constructor(message = "response was cut off before the end") {
6
+ super(message);
7
+ this.name = "OutputTruncatedError";
8
+ }
9
+ }
10
+ /** Provider refused or returned something unusable. Not retried as-is. */
11
+ export class ProviderError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "ProviderError";
15
+ }
16
+ }
17
+ /** Default limits for LLM providers: many keys per call, bounded output size. */
18
+ export const LLM_LIMITS = { maxItems: 40, maxChars: 8000 };
package/dist/retry.js ADDED
@@ -0,0 +1,66 @@
1
+ /** HTTP error with enough detail to decide whether to retry. */
2
+ export class HttpError extends Error {
3
+ status;
4
+ retryAfterMs;
5
+ constructor(status, message, retryAfterMs = null) {
6
+ super(message);
7
+ this.name = "HttpError";
8
+ this.status = status;
9
+ this.retryAfterMs = retryAfterMs;
10
+ }
11
+ }
12
+ /** Parse a Retry-After header (seconds or HTTP date) into milliseconds. */
13
+ export function parseRetryAfter(value) {
14
+ if (!value)
15
+ return null;
16
+ const secs = Number(value);
17
+ if (Number.isFinite(secs))
18
+ return Math.max(0, secs * 1000);
19
+ const date = Date.parse(value);
20
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
21
+ }
22
+ /** 429 (rate limit), 408, 5xx and network failures are worth retrying. */
23
+ export function isRetryable(err) {
24
+ if (err instanceof HttpError)
25
+ return err.status === 429 || err.status === 408 || err.status >= 500;
26
+ // fetch() throws TypeError on network failures (DNS, connection reset).
27
+ return err instanceof TypeError;
28
+ }
29
+ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
30
+ /**
31
+ * Run fn, retrying on rate limits and transient errors with exponential
32
+ * backoff and jitter. A Retry-After header wins over the computed delay.
33
+ */
34
+ export async function withRetry(fn, opts = {}) {
35
+ const retries = opts.retries ?? 5;
36
+ const base = opts.baseDelayMs ?? 1000;
37
+ const max = opts.maxDelayMs ?? 60_000;
38
+ const sleep = opts.sleep ?? defaultSleep;
39
+ for (let attempt = 0;; attempt++) {
40
+ try {
41
+ return await fn();
42
+ }
43
+ catch (err) {
44
+ if (attempt >= retries || !isRetryable(err))
45
+ throw err;
46
+ const backoff = Math.min(max, base * 2 ** attempt) * (0.5 + Math.random() / 2);
47
+ const delay = err instanceof HttpError && err.retryAfterMs !== null ? Math.min(max, err.retryAfterMs) : backoff;
48
+ opts.onRetry?.(attempt + 1, delay, err);
49
+ await sleep(delay);
50
+ }
51
+ }
52
+ }
53
+ /** fetch + JSON with HttpError on non-2xx. */
54
+ export async function fetchJson(url, init) {
55
+ const res = await fetch(url, init);
56
+ const text = await res.text();
57
+ if (!res.ok) {
58
+ throw new HttpError(res.status, `${init.method ?? "GET"} ${url} -> HTTP ${res.status}: ${text.slice(0, 300)}`, parseRetryAfter(res.headers.get("retry-after")));
59
+ }
60
+ try {
61
+ return JSON.parse(text);
62
+ }
63
+ catch {
64
+ throw new Error(`${url}: response is not JSON: ${text.slice(0, 200)}`);
65
+ }
66
+ }
package/dist/stale.js ADDED
@@ -0,0 +1,151 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { LISTING_FIELDS, listingPath, loadListing, readListingFile } from "./listing.js";
4
+ import { messagesPath, readMessagesFile } from "./messages.js";
5
+ import { STATE_VERSION, hashSource, statePath } from "./state.js";
6
+ /**
7
+ * Stale strings: a locale has a translation for a key, but the source text (or
8
+ * its placeholders) changed after that translation was made. Found by comparing
9
+ * the sourceHash in .localizer/state.json with the hash of the current source.
10
+ * This is the same comparison `translate` uses to plan "changed" keys.
11
+ */
12
+ export const STALE_MODES = ["error", "warning", "off"];
13
+ function findKey(data, key) {
14
+ if (Object.hasOwn(data, key))
15
+ return key;
16
+ const lower = key.toLowerCase();
17
+ return Object.keys(data).find((k) => k.toLowerCase() === lower);
18
+ }
19
+ /**
20
+ * Compute stale issues. `listingDirRel` is the listing folder relative to root.
21
+ * Issues carry kind "stale" (one per stale string) or kind "state" (the state file
22
+ * cannot be used).
23
+ */
24
+ export function findStale(project, source, listingDirRel, mode) {
25
+ const issues = [];
26
+ const done = (status, note, untracked = 0) => ({
27
+ issues,
28
+ check: { mode, status, stale: issues.filter((i) => i.kind === "stale").length, untracked, note },
29
+ });
30
+ if (mode === "off")
31
+ return done("off", "Stale check is off (--stale=off).");
32
+ const level = mode;
33
+ const stateIssue = (message, lvl = level) => issues.push({ level: lvl, kind: "state", locale: null, message, file: ".localizer/state.json" });
34
+ const path = statePath(project.root);
35
+ if (!existsSync(path)) {
36
+ return done("no-state", "No .localizer/state.json, so stale strings were not checked. Run translate once and commit the state file.");
37
+ }
38
+ let state;
39
+ try {
40
+ state = JSON.parse(readFileSync(path, "utf8"));
41
+ }
42
+ catch (e) {
43
+ const note = `.localizer/state.json does not parse (${e.message}), so stale strings could not be checked`;
44
+ stateIssue(note);
45
+ return done("bad-state", note);
46
+ }
47
+ if (!state || typeof state !== "object" || state.version !== STATE_VERSION) {
48
+ const note = `.localizer/state.json has version ${JSON.stringify(state?.version)}; this tool knows version ${STATE_VERSION}, so stale strings could not be checked`;
49
+ stateIssue(note);
50
+ return done("unknown-version", note);
51
+ }
52
+ if (state.sourceLocale !== project.defaultLocale) {
53
+ const note = `.localizer/state.json was made for source locale "${String(state.sourceLocale)}", but default_locale is "${project.defaultLocale}"; the next translate run resets it. Stale strings were not checked`;
54
+ stateIssue(note, "warning");
55
+ return done("source-locale-changed", note);
56
+ }
57
+ let untracked = 0;
58
+ const locales = Object.keys(state.locales ?? {}).sort();
59
+ // _locales messages
60
+ const sourceHashes = new Map();
61
+ for (const [key, msg] of Object.entries(source)) {
62
+ if (msg && typeof msg === "object" && typeof msg.message === "string") {
63
+ sourceHashes.set(key, hashSource(msg));
64
+ }
65
+ }
66
+ for (const locale of locales) {
67
+ if (locale === project.defaultLocale)
68
+ continue;
69
+ const p = messagesPath(project.localesDir, locale);
70
+ if (!existsSync(p))
71
+ continue;
72
+ const r = readMessagesFile(p);
73
+ if (!r.ok)
74
+ continue; // reported by the other checks
75
+ const entries = state.locales?.[locale]?.messages ?? {};
76
+ for (const [key, hash] of sourceHashes) {
77
+ const tKey = findKey(r.data, key);
78
+ if (tKey === undefined)
79
+ continue; // missing: reported by the other checks
80
+ const tMsg = r.data[tKey]?.message;
81
+ if (typeof tMsg !== "string" || tMsg.trim() === "")
82
+ continue;
83
+ const entry = entries[key];
84
+ if (!entry) {
85
+ untracked++;
86
+ continue;
87
+ }
88
+ if (entry.sourceHash !== hash) {
89
+ issues.push({
90
+ level,
91
+ kind: "stale",
92
+ locale,
93
+ key,
94
+ message: `source changed after translation (by ${entry.by}); run "ext-localize translate" to update`,
95
+ file: `_locales/${locale}/messages.json`,
96
+ });
97
+ }
98
+ }
99
+ }
100
+ // Store listing (only when the source listing loads)
101
+ const dir = join(project.root, listingDirRel);
102
+ if (existsSync(dir)) {
103
+ let listingSource = null;
104
+ try {
105
+ listingSource = loadListing(project, dir).source;
106
+ }
107
+ catch {
108
+ listingSource = null; // reported by the listing checks
109
+ }
110
+ if (listingSource) {
111
+ for (const locale of locales) {
112
+ if (locale === project.defaultLocale)
113
+ continue;
114
+ const p = listingPath(dir, locale);
115
+ if (!existsSync(p))
116
+ continue;
117
+ const r = readListingFile(p);
118
+ if (!r.ok)
119
+ continue;
120
+ const entries = state.locales?.[locale]?.listing ?? {};
121
+ for (const field of LISTING_FIELDS) {
122
+ const text = r.data[field];
123
+ const src = listingSource[field];
124
+ if (src === undefined || typeof text !== "string" || text.trim() === "")
125
+ continue;
126
+ const entry = entries[field];
127
+ if (!entry) {
128
+ untracked++;
129
+ continue;
130
+ }
131
+ // Copied from _locales: always re-copied by translate --listing, so never "changed".
132
+ // A stale copy shows up as the _locales message being stale, or as a sync warning.
133
+ if (entry.by === "_locales")
134
+ continue;
135
+ if (entry.sourceHash !== hashSource({ message: src })) {
136
+ issues.push({
137
+ level,
138
+ kind: "stale",
139
+ locale,
140
+ key: `listing.${field}`,
141
+ message: `listing source changed after translation (by ${entry.by}); run "ext-localize translate --listing" to update`,
142
+ file: `${listingDirRel.replace(/\\/g, "/").replace(/\/+$/, "")}/${locale}.json`,
143
+ });
144
+ }
145
+ }
146
+ }
147
+ }
148
+ }
149
+ const n = issues.filter((i) => i.kind === "stale").length;
150
+ return done("ok", n ? `${n} translated string(s) are older than their source text.` : "No stale strings.", untracked);
151
+ }
package/dist/state.js ADDED
@@ -0,0 +1,201 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { writeJsonAtomic } from "./messages.js";
5
+ import { placeholdersMatch } from "./placeholders.js";
6
+ /**
7
+ * .localizer/state.json — see README "State file format".
8
+ *
9
+ * {
10
+ * "version": 1,
11
+ * "sourceLocale": "en",
12
+ * "locales": {
13
+ * "de": {
14
+ * "messages": {
15
+ * "extName": { "sourceHash": "<sha256>", "targetHash": "<sha256>", "by": "deepl" }
16
+ * }
17
+ * }
18
+ * }
19
+ * }
20
+ *
21
+ * Keys are sorted on write so the file diffs cleanly in git.
22
+ */
23
+ export const STATE_VERSION = 1;
24
+ export const STATE_DIR = ".localizer";
25
+ export const STATE_FILE = "state.json";
26
+ function sha256(text) {
27
+ return createHash("sha256").update(text, "utf8").digest("hex");
28
+ }
29
+ /**
30
+ * Hash of what a translation depends on: the message text and the
31
+ * placeholders block (names lower-cased, sorted). The description is NOT
32
+ * part of the hash: editing a description does not force re-translation.
33
+ */
34
+ export function hashSource(msg) {
35
+ const ph = msg.placeholders ?? {};
36
+ const placeholders = Object.keys(ph)
37
+ .map((name) => [name.toLowerCase(), ph[name]?.content ?? ""])
38
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
39
+ return sha256(JSON.stringify({ message: msg.message, placeholders }));
40
+ }
41
+ export function hashTarget(message) {
42
+ return sha256(message);
43
+ }
44
+ export function statePath(root) {
45
+ return join(root, STATE_DIR, STATE_FILE);
46
+ }
47
+ export function emptyState(sourceLocale) {
48
+ return { version: STATE_VERSION, sourceLocale, locales: {} };
49
+ }
50
+ export function loadState(root, sourceLocale) {
51
+ const path = statePath(root);
52
+ if (!existsSync(path))
53
+ return emptyState(sourceLocale);
54
+ const data = JSON.parse(readFileSync(path, "utf8"));
55
+ if (data.version !== STATE_VERSION) {
56
+ throw new Error(`${path}: unsupported state version ${data.version} (this tool writes version ${STATE_VERSION})`);
57
+ }
58
+ if (data.sourceLocale !== sourceLocale) {
59
+ // The default locale changed: old hashes describe another language.
60
+ return emptyState(sourceLocale);
61
+ }
62
+ data.locales ??= {};
63
+ return data;
64
+ }
65
+ function sortObject(obj) {
66
+ const out = {};
67
+ for (const k of Object.keys(obj).sort())
68
+ out[k] = obj[k];
69
+ return out;
70
+ }
71
+ /** Write the state file. Returns false (and writes nothing) when the content is the same. */
72
+ export function saveState(root, state) {
73
+ const locales = {};
74
+ for (const [loc, ls] of Object.entries(sortObject(state.locales))) {
75
+ const out = { messages: sortObject(ls.messages ?? {}) };
76
+ if (ls.listing && Object.keys(ls.listing).length)
77
+ out.listing = sortObject(ls.listing);
78
+ locales[loc] = out;
79
+ }
80
+ const data = { version: STATE_VERSION, sourceLocale: state.sourceLocale, locales };
81
+ const path = statePath(root);
82
+ try {
83
+ if (readFileSync(path, "utf8") === JSON.stringify(data, null, 2) + "\n")
84
+ return false;
85
+ }
86
+ catch {
87
+ // no file yet
88
+ }
89
+ writeJsonAtomic(path, data);
90
+ return true;
91
+ }
92
+ function findKey(data, key) {
93
+ if (key in data)
94
+ return key;
95
+ const lower = key.toLowerCase();
96
+ return Object.keys(data).find((k) => k.toLowerCase() === lower);
97
+ }
98
+ /**
99
+ * Decide what to do for one locale.
100
+ *
101
+ * - key missing in target -> translate ("new" if never seen, else "missing")
102
+ * - target message broken (not a string, empty, placeholder set differs) -> translate ("invalid")
103
+ * - state hash differs from current source -> translate ("changed")
104
+ * - no state entry but target has the key -> keep and adopt (we never overwrite
105
+ * existing translations on the first run)
106
+ * - otherwise -> keep
107
+ * - --force -> translate everything ("forced")
108
+ */
109
+ export function planLocale(source, target, localeState, locale, opts = {}) {
110
+ const plan = { locale, translate: [], remove: [], keep: [], adopt: [], manual: [] };
111
+ const tgt = target ?? {};
112
+ const entries = localeState?.messages ?? {};
113
+ const formatOk = (src, tgtMsg) => opts.checkFormat === false || placeholdersMatch(src, tgtMsg);
114
+ for (const [key, src] of Object.entries(source)) {
115
+ const entry = entries[key];
116
+ const tKey = findKey(tgt, key);
117
+ const tVal = tKey !== undefined ? tgt[tKey] : undefined;
118
+ const tMsg = tVal && typeof tVal === "object" && typeof tVal.message === "string" ? tVal.message : undefined;
119
+ if (opts.force) {
120
+ plan.translate.push({ key, reason: "forced" });
121
+ }
122
+ else if (tKey === undefined) {
123
+ plan.translate.push({ key, reason: entry ? "missing" : "new" });
124
+ }
125
+ else if (tMsg === undefined || tMsg.trim() === "" || !formatOk(src.message, tMsg)) {
126
+ plan.translate.push({ key, reason: "invalid" });
127
+ }
128
+ else if (!entry) {
129
+ plan.keep.push(key);
130
+ plan.adopt.push(key);
131
+ }
132
+ else if (entry.sourceHash !== hashSource(src)) {
133
+ plan.translate.push({ key, reason: "changed" });
134
+ }
135
+ else {
136
+ plan.keep.push(key);
137
+ if (entry.targetHash !== hashTarget(tMsg))
138
+ plan.manual.push(key);
139
+ }
140
+ }
141
+ const sourceLower = new Set(Object.keys(source).map((k) => k.toLowerCase()));
142
+ for (const key of Object.keys(tgt)) {
143
+ if (!sourceLower.has(key.toLowerCase()))
144
+ plan.remove.push(key);
145
+ }
146
+ return plan;
147
+ }
148
+ /**
149
+ * Build the new target file and the new locale state after translation.
150
+ * `translated` holds only keys that passed validation. Keys that failed keep
151
+ * their old text (if any) and their old state entry, so the next run retries.
152
+ * Output key order follows the source file.
153
+ */
154
+ export function applyPlan(source, target, localeState, plan, translated, by) {
155
+ const tgt = target ?? {};
156
+ const oldEntries = localeState?.messages ?? {};
157
+ const file = {};
158
+ const messages = {};
159
+ const keep = new Set(plan.keep);
160
+ const adopt = new Set(plan.adopt);
161
+ const manual = new Set(plan.manual);
162
+ const reasonOf = new Map(plan.translate.map((t) => [t.key, t.reason]));
163
+ for (const [key, src] of Object.entries(source)) {
164
+ const sourceHash = hashSource(src);
165
+ const newText = translated[key];
166
+ if (newText !== undefined) {
167
+ file[key] = buildEntry(src, newText);
168
+ messages[key] = { sourceHash, targetHash: hashTarget(newText), by };
169
+ continue;
170
+ }
171
+ const tKey = findKey(tgt, key);
172
+ const old = tKey !== undefined ? tgt[tKey] : undefined;
173
+ const oldUsable = old && typeof old === "object" && typeof old.message === "string" && old.message.trim() !== "";
174
+ if (keep.has(key) && old) {
175
+ file[key] = old;
176
+ if (adopt.has(key))
177
+ messages[key] = { sourceHash, targetHash: hashTarget(old.message), by: "adopted" };
178
+ else if (manual.has(key))
179
+ messages[key] = { sourceHash, targetHash: hashTarget(old.message), by: "manual" };
180
+ else if (oldEntries[key])
181
+ messages[key] = oldEntries[key];
182
+ }
183
+ else {
184
+ // Failed this run: keep the old text if it is usable (a broken one is dropped,
185
+ // so Chrome falls back to the default locale), keep the old state entry.
186
+ if (oldUsable && reasonOf.get(key) !== "invalid")
187
+ file[key] = old;
188
+ if (oldEntries[key])
189
+ messages[key] = oldEntries[key];
190
+ }
191
+ }
192
+ return { file, state: { messages } };
193
+ }
194
+ function buildEntry(src, message) {
195
+ const entry = { message };
196
+ if (src.description !== undefined)
197
+ entry.description = src.description;
198
+ if (src.placeholders !== undefined)
199
+ entry.placeholders = src.placeholders;
200
+ return entry;
201
+ }