ext-localize 0.0.0-stage → 0.2.1

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/dist/stale.js ADDED
@@ -0,0 +1,152 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { resolve } 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
+ import { relPath } from "./paths.js";
7
+ /**
8
+ * Stale strings: a locale has a translation for a key, but the source text (or
9
+ * its placeholders) changed after that translation was made. Found by comparing
10
+ * the sourceHash in .localizer/state.json with the hash of the current source.
11
+ * This is the same comparison `translate` uses to plan "changed" keys.
12
+ */
13
+ export const STALE_MODES = ["error", "warning", "off"];
14
+ function findKey(data, key) {
15
+ if (Object.hasOwn(data, key))
16
+ return key;
17
+ const lower = key.toLowerCase();
18
+ return Object.keys(data).find((k) => k.toLowerCase() === lower);
19
+ }
20
+ /**
21
+ * Compute stale issues. `listingDirRel` is the listing folder relative to root.
22
+ * Issues carry kind "stale" (one per stale string) or kind "state" (the state file
23
+ * cannot be used).
24
+ */
25
+ export function findStale(project, source, listingDirRel, mode) {
26
+ const issues = [];
27
+ const done = (status, note, untracked = 0) => ({
28
+ issues,
29
+ check: { mode, status, stale: issues.filter((i) => i.kind === "stale").length, untracked, note },
30
+ });
31
+ if (mode === "off")
32
+ return done("off", "Stale check is off (--stale=off).");
33
+ const level = mode;
34
+ const stateIssue = (message, lvl = level) => issues.push({ level: lvl, kind: "state", locale: null, message, file: relPath(project.root, statePath(project.root)) });
35
+ const path = statePath(project.root);
36
+ if (!existsSync(path)) {
37
+ return done("no-state", "No .localizer/state.json, so stale strings were not checked. Run translate once and commit the state file.");
38
+ }
39
+ let state;
40
+ try {
41
+ state = JSON.parse(readFileSync(path, "utf8"));
42
+ }
43
+ catch (e) {
44
+ const note = `.localizer/state.json does not parse (${e.message}), so stale strings could not be checked`;
45
+ stateIssue(note);
46
+ return done("bad-state", note);
47
+ }
48
+ if (!state || typeof state !== "object" || state.version !== STATE_VERSION) {
49
+ const note = `.localizer/state.json has version ${JSON.stringify(state?.version)}; this tool knows version ${STATE_VERSION}, so stale strings could not be checked`;
50
+ stateIssue(note);
51
+ return done("unknown-version", note);
52
+ }
53
+ if (state.sourceLocale !== project.defaultLocale) {
54
+ 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`;
55
+ stateIssue(note, "warning");
56
+ return done("source-locale-changed", note);
57
+ }
58
+ let untracked = 0;
59
+ const locales = Object.keys(state.locales ?? {}).sort();
60
+ // _locales messages
61
+ const sourceHashes = new Map();
62
+ for (const [key, msg] of Object.entries(source)) {
63
+ if (msg && typeof msg === "object" && typeof msg.message === "string") {
64
+ sourceHashes.set(key, hashSource(msg));
65
+ }
66
+ }
67
+ for (const locale of locales) {
68
+ if (locale === project.defaultLocale)
69
+ continue;
70
+ const p = messagesPath(project.localesDir, locale);
71
+ if (!existsSync(p))
72
+ continue;
73
+ const r = readMessagesFile(p);
74
+ if (!r.ok)
75
+ continue; // reported by the other checks
76
+ const entries = state.locales?.[locale]?.messages ?? {};
77
+ for (const [key, hash] of sourceHashes) {
78
+ const tKey = findKey(r.data, key);
79
+ if (tKey === undefined)
80
+ continue; // missing: reported by the other checks
81
+ const tMsg = r.data[tKey]?.message;
82
+ if (typeof tMsg !== "string" || tMsg.trim() === "")
83
+ continue;
84
+ const entry = entries[key];
85
+ if (!entry) {
86
+ untracked++;
87
+ continue;
88
+ }
89
+ if (entry.sourceHash !== hash) {
90
+ issues.push({
91
+ level,
92
+ kind: "stale",
93
+ locale,
94
+ key,
95
+ message: `source changed after translation (by ${entry.by}); run "ext-localize translate" to update`,
96
+ file: `_locales/${locale}/messages.json`,
97
+ });
98
+ }
99
+ }
100
+ }
101
+ // Store listing (only when the source listing loads)
102
+ const dir = resolve(project.root, listingDirRel);
103
+ if (existsSync(dir)) {
104
+ let listingSource = null;
105
+ try {
106
+ listingSource = loadListing(project, dir).source;
107
+ }
108
+ catch {
109
+ listingSource = null; // reported by the listing checks
110
+ }
111
+ if (listingSource) {
112
+ for (const locale of locales) {
113
+ if (locale === project.defaultLocale)
114
+ continue;
115
+ const p = listingPath(dir, locale);
116
+ if (!existsSync(p))
117
+ continue;
118
+ const r = readListingFile(p);
119
+ if (!r.ok)
120
+ continue;
121
+ const entries = state.locales?.[locale]?.listing ?? {};
122
+ for (const field of LISTING_FIELDS) {
123
+ const text = r.data[field];
124
+ const src = listingSource[field];
125
+ if (src === undefined || typeof text !== "string" || text.trim() === "")
126
+ continue;
127
+ const entry = entries[field];
128
+ if (!entry) {
129
+ untracked++;
130
+ continue;
131
+ }
132
+ // Copied from _locales: always re-copied by translate --listing, so never "changed".
133
+ // A stale copy shows up as the _locales message being stale, or as a sync warning.
134
+ if (entry.by === "_locales")
135
+ continue;
136
+ if (entry.sourceHash !== hashSource({ message: src })) {
137
+ issues.push({
138
+ level,
139
+ kind: "stale",
140
+ locale,
141
+ key: `listing.${field}`,
142
+ message: `listing source changed after translation (by ${entry.by}); run "ext-localize translate --listing" to update`,
143
+ file: relPath(project.root, listingPath(dir, locale)),
144
+ });
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ const n = issues.filter((i) => i.kind === "stale").length;
151
+ return done("ok", n ? `${n} translated string(s) are older than their source text.` : "No stale strings.", untracked);
152
+ }
package/dist/state.js ADDED
@@ -0,0 +1,237 @@
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 { localizerDir } from "./paths.js";
6
+ import { placeholdersMatch } from "./placeholders.js";
7
+ import { familyMember, pluralFamilies, splitPluralKey } from "./plurals.js";
8
+ /**
9
+ * .localizer/state.json — see README "State file format".
10
+ *
11
+ * {
12
+ * "version": 1,
13
+ * "sourceLocale": "en",
14
+ * "locales": {
15
+ * "de": {
16
+ * "messages": {
17
+ * "extName": { "sourceHash": "<sha256>", "targetHash": "<sha256>", "by": "deepl" }
18
+ * }
19
+ * }
20
+ * }
21
+ * }
22
+ *
23
+ * Keys are sorted on write so the file diffs cleanly in git.
24
+ */
25
+ export const STATE_VERSION = 1;
26
+ export const STATE_DIR = ".localizer";
27
+ export const STATE_FILE = "state.json";
28
+ function sha256(text) {
29
+ return createHash("sha256").update(text, "utf8").digest("hex");
30
+ }
31
+ /**
32
+ * Hash of what a translation depends on: the message text and the
33
+ * placeholders block (names lower-cased, sorted). The description is NOT
34
+ * part of the hash: editing a description does not force re-translation.
35
+ */
36
+ export function hashSource(msg) {
37
+ const ph = msg.placeholders ?? {};
38
+ const placeholders = Object.keys(ph)
39
+ .map((name) => [name.toLowerCase(), ph[name]?.content ?? ""])
40
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
41
+ return sha256(JSON.stringify({ message: msg.message, placeholders }));
42
+ }
43
+ export function hashTarget(message) {
44
+ return sha256(message);
45
+ }
46
+ export function statePath(root) {
47
+ return join(localizerDir(root), STATE_FILE);
48
+ }
49
+ export function emptyState(sourceLocale) {
50
+ return { version: STATE_VERSION, sourceLocale, locales: {} };
51
+ }
52
+ export function loadState(root, sourceLocale) {
53
+ const path = statePath(root);
54
+ if (!existsSync(path))
55
+ return emptyState(sourceLocale);
56
+ const data = JSON.parse(readFileSync(path, "utf8"));
57
+ if (data.version !== STATE_VERSION) {
58
+ throw new Error(`${path}: unsupported state version ${data.version} (this tool writes version ${STATE_VERSION})`);
59
+ }
60
+ if (data.sourceLocale !== sourceLocale) {
61
+ // The default locale changed: old hashes describe another language.
62
+ return emptyState(sourceLocale);
63
+ }
64
+ data.locales ??= {};
65
+ return data;
66
+ }
67
+ function sortObject(obj) {
68
+ const out = {};
69
+ for (const k of Object.keys(obj).sort())
70
+ out[k] = obj[k];
71
+ return out;
72
+ }
73
+ /** Write the state file. Returns false (and writes nothing) when the content is the same. */
74
+ export function saveState(root, state) {
75
+ const locales = {};
76
+ for (const [loc, ls] of Object.entries(sortObject(state.locales))) {
77
+ const out = { messages: sortObject(ls.messages ?? {}) };
78
+ if (ls.listing && Object.keys(ls.listing).length)
79
+ out.listing = sortObject(ls.listing);
80
+ locales[loc] = out;
81
+ }
82
+ const data = { version: STATE_VERSION, sourceLocale: state.sourceLocale, locales };
83
+ const path = statePath(root);
84
+ try {
85
+ if (readFileSync(path, "utf8") === JSON.stringify(data, null, 2) + "\n")
86
+ return false;
87
+ }
88
+ catch {
89
+ // no file yet
90
+ }
91
+ writeJsonAtomic(path, data);
92
+ return true;
93
+ }
94
+ function findKey(data, key) {
95
+ if (key in data)
96
+ return key;
97
+ const lower = key.toLowerCase();
98
+ return Object.keys(data).find((k) => k.toLowerCase() === lower);
99
+ }
100
+ /**
101
+ * Decide what to do for one locale.
102
+ *
103
+ * - key missing in target -> translate ("new" if never seen, else "missing")
104
+ * - target message broken (not a string, empty, placeholder set differs) -> translate ("invalid")
105
+ * - state hash differs from current source -> translate ("changed")
106
+ * - no state entry but target has the key -> keep and adopt (we never overwrite
107
+ * existing translations on the first run)
108
+ * - otherwise -> keep
109
+ * - --force -> translate everything ("forced")
110
+ */
111
+ export function planLocale(source, target, localeState, locale, opts = {}) {
112
+ const plan = { locale, translate: [], remove: [], keep: [], adopt: [], manual: [] };
113
+ const tgt = target ?? {};
114
+ const entries = localeState?.messages ?? {};
115
+ const formatOk = (src, tgtMsg) => opts.checkFormat === false || placeholdersMatch(src, tgtMsg);
116
+ // CLDR plural families: a locale only needs the categories its language uses.
117
+ const families = pluralFamilies(Object.keys(source));
118
+ for (const [key, src] of Object.entries(source)) {
119
+ const entry = entries[key];
120
+ const tKey = findKey(tgt, key);
121
+ const tVal = tKey !== undefined ? tgt[tKey] : undefined;
122
+ const tMsg = tVal && typeof tVal === "object" && typeof tVal.message === "string" ? tVal.message : undefined;
123
+ const member = familyMember(key, families, locale);
124
+ if (member && !member.used && tKey === undefined) {
125
+ continue; // e.g. items_one for Japanese: not needed, not written
126
+ }
127
+ if (opts.force) {
128
+ plan.translate.push({ key, reason: "forced" });
129
+ }
130
+ else if (tKey === undefined) {
131
+ plan.translate.push({ key, reason: entry ? "missing" : "new" });
132
+ }
133
+ else if (tMsg === undefined || tMsg.trim() === "" || !formatOk(src.message, tMsg)) {
134
+ plan.translate.push({ key, reason: "invalid" });
135
+ }
136
+ else if (!entry) {
137
+ plan.keep.push(key);
138
+ plan.adopt.push(key);
139
+ }
140
+ else if (entry.sourceHash !== hashSource(src)) {
141
+ plan.translate.push({ key, reason: "changed" });
142
+ }
143
+ else {
144
+ plan.keep.push(key);
145
+ if (entry.targetHash !== hashTarget(tMsg))
146
+ plan.manual.push(key);
147
+ }
148
+ }
149
+ const sourceLower = new Set(Object.keys(source).map((k) => k.toLowerCase()));
150
+ for (const key of Object.keys(tgt)) {
151
+ // Extra keys of a plural family (items_few in Russian) belong to the locale: kept.
152
+ if (!sourceLower.has(key.toLowerCase()) && !familyMember(key, families, locale))
153
+ plan.remove.push(key);
154
+ }
155
+ return plan;
156
+ }
157
+ /**
158
+ * Build the new target file and the new locale state after translation.
159
+ * `translated` holds only keys that passed validation. Keys that failed keep
160
+ * their old text (if any) and their old state entry, so the next run retries.
161
+ * Output key order follows the source file.
162
+ */
163
+ export function applyPlan(source, target, localeState, plan, translated, by) {
164
+ const tgt = target ?? {};
165
+ const oldEntries = localeState?.messages ?? {};
166
+ const file = {};
167
+ const messages = {};
168
+ const keep = new Set(plan.keep);
169
+ const adopt = new Set(plan.adopt);
170
+ const manual = new Set(plan.manual);
171
+ const reasonOf = new Map(plan.translate.map((t) => [t.key, t.reason]));
172
+ // Target keys of a source plural family that the source does not have (items_few):
173
+ // written right after the last source key of their family.
174
+ const families = pluralFamilies(Object.keys(source));
175
+ const sourceLower = new Set(Object.keys(source).map((k) => k.toLowerCase()));
176
+ const extras = new Map();
177
+ for (const k of Object.keys(tgt)) {
178
+ const m = familyMember(k, families, plan.locale);
179
+ if (m && !sourceLower.has(k.toLowerCase()))
180
+ extras.set(m.base, [...(extras.get(m.base) ?? []), k]);
181
+ }
182
+ const lastOfFamily = new Map();
183
+ for (const k of Object.keys(source)) {
184
+ const p = splitPluralKey(k);
185
+ if (p && families.has(p.base))
186
+ lastOfFamily.set(p.base, k);
187
+ }
188
+ const addExtras = (key) => {
189
+ const p = splitPluralKey(key);
190
+ if (!p || lastOfFamily.get(p.base) !== key)
191
+ return;
192
+ for (const k of extras.get(p.base) ?? [])
193
+ file[k] = tgt[k];
194
+ };
195
+ for (const [key, src] of Object.entries(source)) {
196
+ applyOne(key, src);
197
+ addExtras(key);
198
+ }
199
+ return { file, state: { messages } };
200
+ function applyOne(key, src) {
201
+ const sourceHash = hashSource(src);
202
+ const newText = translated[key];
203
+ if (newText !== undefined) {
204
+ file[key] = buildEntry(src, newText);
205
+ messages[key] = { sourceHash, targetHash: hashTarget(newText), by };
206
+ return;
207
+ }
208
+ const tKey = findKey(tgt, key);
209
+ const old = tKey !== undefined ? tgt[tKey] : undefined;
210
+ const oldUsable = old && typeof old === "object" && typeof old.message === "string" && old.message.trim() !== "";
211
+ if (keep.has(key) && old) {
212
+ file[key] = old;
213
+ if (adopt.has(key))
214
+ messages[key] = { sourceHash, targetHash: hashTarget(old.message), by: "adopted" };
215
+ else if (manual.has(key))
216
+ messages[key] = { sourceHash, targetHash: hashTarget(old.message), by: "manual" };
217
+ else if (oldEntries[key])
218
+ messages[key] = oldEntries[key];
219
+ }
220
+ else {
221
+ // Failed this run: keep the old text if it is usable (a broken one is dropped,
222
+ // so Chrome falls back to the default locale), keep the old state entry.
223
+ if (oldUsable && reasonOf.get(key) !== "invalid")
224
+ file[key] = old;
225
+ if (oldEntries[key])
226
+ messages[key] = oldEntries[key];
227
+ }
228
+ }
229
+ }
230
+ function buildEntry(src, message) {
231
+ const entry = { message };
232
+ if (src.description !== undefined)
233
+ entry.description = src.description;
234
+ if (src.placeholders !== undefined)
235
+ entry.placeholders = src.placeholders;
236
+ return entry;
237
+ }
@@ -0,0 +1,205 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { spawn } from "node:child_process";
10
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join, resolve } from "node:path";
13
+ import { DASHBOARD_URL, checkSaveAllowed, itemFromUrl, readFillCore } from "./chrome.js";
14
+ /**
15
+ * EXPERIMENTAL: fill, save and check the Chrome listing with no paste.
16
+ * Ported from spikes/chrome-listing-delivery/full-flow/run.mjs (route 1: tested on a
17
+ * real test item on 2026-11-17). Google has not confirmed that scripting the
18
+ * dashboard is allowed (Developer Agreement 4.4.2 is unclear).
19
+ *
20
+ * Guards:
21
+ * - --item is required; the open tab must be that item.
22
+ * - Never clicks Publish or Submit for review. Only one button named exactly "Save draft".
23
+ * - Saves only with --save, and only on items in chrome.testItems unless --allow-live.
24
+ * - After saving: reload and read every language back.
25
+ * - Nothing about the network traffic is recorded (the save request holds session tokens).
26
+ */
27
+ export const AUTO_WARNING = `WARNING: --auto is EXPERIMENTAL.
28
+ It drives the Chrome Web Store dashboard from a script over the DevTools Protocol.
29
+ Google has NOT confirmed that this is allowed. The Developer Agreement (section 4.4.2)
30
+ forbids access "by any means other than through the interface", and it is unclear
31
+ whether a script that clicks the same interface counts. Your publisher account is
32
+ what is at risk. The default, lower-risk way is "ext-localize push chrome" (one paste).`;
33
+ export const DEFAULT_PROFILE = join(homedir(), ".ext-localize", "chrome-profile");
34
+ export const MAC_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
35
+ /** Playwright is an optional peer dependency: only --auto needs it. */
36
+ export async function loadPlaywright() {
37
+ for (const name of ["playwright-core", "playwright"]) {
38
+ try {
39
+ const mod = (await import(__rewriteRelativeImportExtension(name)));
40
+ const chromium = mod.chromium ?? mod.default?.chromium;
41
+ if (chromium)
42
+ return { chromium };
43
+ }
44
+ catch {
45
+ // try the next one
46
+ }
47
+ }
48
+ throw new Error(`--auto needs Playwright, which is not installed (it is optional to keep the default install small).\n` +
49
+ `Install it next to ext-localize: npm install playwright-core\n` +
50
+ `It uses your installed Google Chrome; no browser download is needed.`);
51
+ }
52
+ /** Open plain Chrome (no automation) on the --auto profile, so you can sign in to Google once. */
53
+ export function openLoginBrowser(profile, executable = MAC_CHROME) {
54
+ if (!existsSync(executable))
55
+ throw new Error(`Google Chrome not found at ${executable}`);
56
+ mkdirSync(profile, { recursive: true });
57
+ const child = spawn(executable, [`--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", DASHBOARD_URL], {
58
+ detached: true,
59
+ stdio: "ignore",
60
+ });
61
+ child.unref();
62
+ }
63
+ async function getBrowser(pw, o) {
64
+ const how = o.browser ?? "launch";
65
+ if (how === "launch") {
66
+ const profile = resolve(o.profile ?? DEFAULT_PROFILE);
67
+ mkdirSync(profile, { recursive: true });
68
+ const ctx = await pw.chromium.launchPersistentContext(profile, {
69
+ channel: "chrome",
70
+ headless: o.headless ?? false,
71
+ viewport: null,
72
+ // Without these, Chrome cannot read cookies saved by plain Chrome (the Google sign-in).
73
+ ignoreDefaultArgs: ["--use-mock-keychain", "--password-store=basic"],
74
+ });
75
+ return { ctx, done: () => ctx.close() };
76
+ }
77
+ const port = /^port:(\d+)$/.exec(how);
78
+ if (!port)
79
+ throw new Error(`--browser must be "launch" or "port:<number>", not "${how}"`);
80
+ const browser = await pw.chromium.connectOverCDP(`http://127.0.0.1:${port[1]}`, { timeout: 30000 });
81
+ const ctx = browser.contexts()[0];
82
+ if (!ctx)
83
+ throw new Error("connected, but Chrome has no browser context");
84
+ // Disconnect only; the Chrome you started stays open.
85
+ return { ctx, done: () => browser.close() };
86
+ }
87
+ async function findDashboardPage(ctx, o) {
88
+ const want = (p) => itemFromUrl(p.url()) === o.item;
89
+ const open = ctx.pages().find(want);
90
+ if (open)
91
+ return open;
92
+ const page = await ctx.newPage();
93
+ const start = o.url ?? (o.publisher ? `${DASHBOARD_URL}${o.publisher}/${o.item}/edit` : DASHBOARD_URL);
94
+ await page.goto(start);
95
+ if (want(page))
96
+ return page;
97
+ o.log?.(`Open item ${o.item} and its "Store listing" tab in this window. Waiting up to ${Math.round((o.waitMs ?? 900000) / 60000)} min.`);
98
+ const end = Date.now() + (o.waitMs ?? 15 * 60 * 1000);
99
+ while (Date.now() < end) {
100
+ for (const p of ctx.pages())
101
+ if (want(p))
102
+ return p;
103
+ await new Promise((r) => setTimeout(r, 1000));
104
+ }
105
+ throw new Error("Timed out waiting for the item page.");
106
+ }
107
+ async function inject(page, core) {
108
+ // DevTools Protocol: not blocked by the page CSP, and not an extension.
109
+ await page.evaluate(core);
110
+ await page.waitForFunction(() => {
111
+ try {
112
+ return !!globalThis.ListingFill.findTextarea();
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }, null, { timeout: 60000 });
118
+ }
119
+ async function fill(page, core, descriptions) {
120
+ await inject(page, core);
121
+ return page.evaluate((l) => globalThis.ListingFill.run(l, {
122
+ mode: "fill-all",
123
+ save: "none",
124
+ verify: true,
125
+ log: () => { },
126
+ }), descriptions);
127
+ }
128
+ /** After a reload: switch to each language and compare the box with the file. Changes nothing. */
129
+ async function verifySaved(page, core, descriptions) {
130
+ await inject(page, core);
131
+ const want = Object.fromEntries(Object.entries(descriptions).map(([k, v]) => [k, v.description]));
132
+ return page.evaluate(async (want) => {
133
+ const L = globalThis.ListingFill;
134
+ const norm = (s) => String(s || "").replace(/\r\n/g, "\n").trim();
135
+ const rows = [];
136
+ for (const loc of Object.keys(want).sort()) {
137
+ try {
138
+ const sel = await L.selectLocale(loc);
139
+ if (!sel.ok) {
140
+ rows.push({ locale: loc, ok: false, error: "language not in dropdown" });
141
+ continue;
142
+ }
143
+ const got = norm(L.findTextarea().el.value);
144
+ const w = norm(want[loc]);
145
+ rows.push({ locale: loc, ok: got === w, gotLength: got.length, wantLength: w.length });
146
+ }
147
+ catch (e) {
148
+ rows.push({ locale: loc, ok: false, error: e.message });
149
+ }
150
+ }
151
+ return { ok: rows.length > 0 && rows.every((r) => r.ok), rows };
152
+ }, want);
153
+ }
154
+ /** Run --auto. Never throws for page problems: they end up in report.error. */
155
+ export async function runAuto(descriptions, o, pw) {
156
+ const log = o.log ?? (() => { });
157
+ const report = { date: new Date().toISOString(), browser: o.browser ?? "launch", item: null };
158
+ // Fail before opening a browser when the flags alone are not enough.
159
+ if (!o.item)
160
+ throw new Error("Refusing: --auto needs --item <itemId>.");
161
+ const playwright = pw ?? (await loadPlaywright());
162
+ const core = readFillCore();
163
+ const b = await getBrowser(playwright, o);
164
+ try {
165
+ const page = await findDashboardPage(b.ctx, o);
166
+ report.item = itemFromUrl(page.url());
167
+ checkSaveAllowed(report.item, o);
168
+ await page.bringToFront().catch(() => { });
169
+ report.fill = await fill(page, core, descriptions);
170
+ report.fillOk = !!report.fill.verify?.ok && !report.fill.errors.length && !report.fill.unmatched.length && !report.fill.tooLong.length;
171
+ log(report.fillOk ? `Filled and checked ${report.fill.filled.length} language(s) (not saved yet).` : "Fill had problems; not saving.");
172
+ if (o.save && report.fillOk) {
173
+ const btn = page.getByRole("button", { name: "Save draft", exact: true });
174
+ const n = await btn.count();
175
+ if (n !== 1)
176
+ throw new Error(`Expected exactly one "Save draft" button, found ${n}.`);
177
+ const label = (await btn.textContent()) ?? "";
178
+ if (/submit|publish|review/i.test(label))
179
+ throw new Error("Refusing: the button text looks like submit or publish.");
180
+ await btn.click(); // a real (trusted) click through the DevTools Protocol
181
+ await page.waitForLoadState("networkidle", { timeout: 30000 }).catch(() => { });
182
+ await page.waitForTimeout(2000);
183
+ report.saved = true;
184
+ log("Clicked Save draft. Reloading to check what was kept.");
185
+ await page.reload({ waitUntil: "domcontentloaded" });
186
+ report.afterReload = await verifySaved(page, core, descriptions);
187
+ log(report.afterReload.ok ? "After reload: every language has the new text." : "After reload: some languages differ. See the report.");
188
+ }
189
+ else if (!o.save) {
190
+ log("No --save: nothing was saved. Reload the page without saving to undo, or click Save draft yourself.");
191
+ }
192
+ }
193
+ catch (e) {
194
+ report.error = e.message;
195
+ }
196
+ finally {
197
+ await b.done().catch(() => { });
198
+ }
199
+ return report;
200
+ }
201
+ export function writeAutoReport(dir, report) {
202
+ const f = join(dir, `chrome-auto-${report.date.replace(/[:.]/g, "-")}.json`);
203
+ writeFileSync(f, JSON.stringify(report, null, 2) + "\n");
204
+ return f;
205
+ }