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/cli.js ADDED
@@ -0,0 +1,722 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { checkProject, formatIssue } from "./check.js";
7
+ import { loadGlossary } from "./glossary.js";
8
+ import { parseTargetLocales } from "./locales.js";
9
+ import { ProjectError, loadProject } from "./messages.js";
10
+ import { createProvider, limitsFor, PROVIDER_NAMES } from "./providers/index.js";
11
+ import { ANTHROPIC_DEFAULT_MODEL } from "./providers/anthropic.js";
12
+ import { FORMALITIES } from "./providers/types.js";
13
+ import { loadState, statePath } from "./state.js";
14
+ import { runJob, translateProject } from "./translate.js";
15
+ import { ConfigError, loadConfig, parseStores } from "./config.js";
16
+ import { clearLocalizerDir, configBase, relPath, setLocalizerDir } from "./paths.js";
17
+ import { recount, zipIssues } from "./zip.js";
18
+ import { importDescriptions } from "./import.js";
19
+ import { UsageError } from "./usage.js";
20
+ import { STALE_MODES } from "./stale.js";
21
+ import { ListingError, defaultListingTargets, listingDir, listingJob, loadListing, readAllListings, } from "./listing.js";
22
+ import { AMO_HOST, AMO_PROD_LOCALES, addonUrl, amoDefaultLocale, buildPatchBody, sendPatch } from "./stores/firefox.js";
23
+ import { buildDiagnoseScript, buildPasteScript, chromeDescriptions, copyToClipboard, isItemId, outDir, } from "./stores/chrome.js";
24
+ import { AUTO_WARNING, DEFAULT_PROFILE, openLoginBrowser, runAuto, writeAutoReport } from "./stores/chrome-auto.js";
25
+ import { edgeBlock, writeEdgeFiles } from "./stores/edge.js";
26
+ const HELP = `ext-localize - translate, check and deliver Chrome extension _locales and store listings
27
+
28
+ Usage:
29
+ ext-localize translate --provider <name> [--to <locales>] [options]
30
+ ext-localize translate --listing --provider <name> [options]
31
+ ext-localize check [options]
32
+ ext-localize push firefox --addon <id> [--send]
33
+ ext-localize push chrome [--copy]
34
+ ext-localize push chrome --auto --item <id> [--save] (EXPERIMENTAL)
35
+ ext-localize push edge [--print]
36
+ ext-localize listing import <folder | "path/{locale}.txt"> [--force]
37
+
38
+ translate options:
39
+ --listing Translate the store listing (listing/<locale>.json) instead of _locales
40
+ --store <list> With --listing: stores whose length limits apply (default: config "stores", else chrome)
41
+ --json Print a machine-readable result on stdout (progress goes to stderr)
42
+ --provider <name> ${PROVIDER_NAMES.join(" | ")}
43
+ --to <locales> "all" (all 55 Chrome locales) or a list: de,fr,pt-BR
44
+ Default: the locale folders that already exist.
45
+ --model <id> Model id. anthropic default: ${ANTHROPIC_DEFAULT_MODEL}.
46
+ Required for openai and ollama.
47
+ --effort <level> anthropic only: low | medium | high | xhigh | max (default: medium)
48
+ --formality <value> default | more | less | prefer_more | prefer_less
49
+ DeepL: its formality setting. LLMs: formal or informal tone.
50
+ --glossary <file> Default: .localizer/glossary.json if it exists
51
+ --dry-run Show what would be translated and the request count. No API calls.
52
+ --force Re-translate every key, even unchanged ones
53
+ --batch-size <n> Max strings per request
54
+ --concurrency <n> Locales translated at the same time (default: 4)
55
+
56
+ check options:
57
+ --json Machine-readable output
58
+ --strict Exit with an error on warnings too
59
+ --store <list> Stores whose listing limits apply: chrome,firefox,edge (default: config "stores", else chrome)
60
+ --stale <level> Stale strings (source changed after translation): warning (default) | error | off
61
+
62
+ push firefox options (dry run unless --send):
63
+ --addon <id> Add-on id, slug or guid (or config firefox.addon)
64
+ --send Really send the PATCH. Needs AMO_JWT_ISSUER and AMO_JWT_SECRET.
65
+ --remove <list> Also delete these AMO locales (sends null)
66
+ --default-locale <c> The add-on default locale on AMO (default: from manifest default_locale)
67
+ --extra-locales <l> AMO locales to accept beyond the built-in list of 44
68
+ --host <url> Default: ${AMO_HOST}
69
+
70
+ push chrome options (default: write a script you paste into the dashboard):
71
+ --copy Also copy the script to the clipboard (macOS)
72
+ --mode <m> fill-all (default) | save-each
73
+ --out <file> Default: .localizer/out/chrome-paste.js
74
+ --auto EXPERIMENTAL: drive the dashboard over the DevTools Protocol (needs playwright-core)
75
+ --item <id> Item id (32 letters). Required with --auto (or config chrome.item).
76
+ --save With --auto: click "Save draft", reload and check. Never Publish or Submit.
77
+ --allow-live With --save: allow an item that is not in config chrome.testItems
78
+ --browser <b> launch (default) | port:<n>
79
+ --profile <dir> Chrome profile for launch (default: ~/.ext-localize/chrome-profile)
80
+ --login Open plain Chrome on that profile to sign in to Google once, then exit
81
+ --zip <file> Warn about listing files the uploaded package (.zip) has no _locales folder for
82
+ The paste script is pure ASCII; its size is printed. Non-Latin text grows about 6x
83
+ (each character is written as a \\uXXXX escape).
84
+
85
+ push edge options:
86
+ --print Print copy-ready blocks instead of only writing files
87
+
88
+ check also:
89
+ --listing-only Only listing checks (and project-level problems)
90
+ --zip <file> Also compare listing files with the _locales in this package (.zip)
91
+
92
+ listing import: turn existing per-locale description files (.txt) into listing/<locale>.json.
93
+ Name and summary come from _locales when the manifest uses __MSG_. --force overwrites.
94
+
95
+ Common:
96
+ --dir <path> Extension folder with manifest.json (default: current folder)
97
+ --config <file> Config file (default: <dir>/.localizer/config.json). state.json,
98
+ glossary.json and out/ are kept next to it. For WXT/Plasmo builds.
99
+ --listing-dir <dir> Listing folder (default: config listing.dir, else <dir>/listing)
100
+ -h, --help Show this help
101
+ -v, --version Show version
102
+
103
+ Exit codes: 0 ok, 1 failed (errors found, strings failed, run stopped), 2 usage or setup error,
104
+ 3 translate had no target locales.
105
+
106
+ Keys are read from the environment only:
107
+ ANTHROPIC_API_KEY, OPENAI_API_KEY (+ OPENAI_BASE_URL), DEEPL_API_KEY, OLLAMA_HOST,
108
+ AMO_JWT_ISSUER, AMO_JWT_SECRET
109
+ Defaults for most options can be set in .localizer/config.json (see README).
110
+ `;
111
+ function version() {
112
+ const here = dirname(fileURLToPath(import.meta.url));
113
+ const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
114
+ return pkg.version;
115
+ }
116
+ function positiveInt(value, flag) {
117
+ if (value === undefined)
118
+ return undefined;
119
+ const n = Number(value);
120
+ if (!Number.isInteger(n) || n < 1)
121
+ throw new UsageError(`${flag} must be a positive whole number`);
122
+ return n;
123
+ }
124
+ function shorten(text, max) {
125
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
126
+ }
127
+ function printPlan(result, dryRun, providerName) {
128
+ const rows = result.locales.map((r) => {
129
+ const count = (reason) => r.plan.translate.filter((t) => t.reason === reason).length;
130
+ return {
131
+ locale: r.locale,
132
+ new: count("new") + count("missing"),
133
+ changed: count("changed"),
134
+ invalid: count("invalid"),
135
+ forced: count("forced"),
136
+ removed: r.plan.remove.length,
137
+ kept: r.plan.keep.length,
138
+ requests: r.requests,
139
+ note: shorten(r.skipped ?? (r.plan.manual.length ? `${r.plan.manual.length} edited by hand (kept)` : ""), 70),
140
+ };
141
+ });
142
+ const head = ["locale", "new", "changed", "invalid", "forced", "removed", "kept", "requests", "note"];
143
+ const table = [head, ...rows.map((r) => head.map((h) => String(r[h])))];
144
+ const widths = head.map((_, i) => Math.max(...table.map((row) => (row[i] ?? "").length)));
145
+ for (const row of table)
146
+ console.log(row.map((c, i) => c.padEnd(widths[i] ?? 0)).join(" ").trimEnd());
147
+ console.log("");
148
+ if (dryRun) {
149
+ const head = `Dry run: ${result.totalStrings} string(s) to translate in ${result.locales.length} locale(s), about ${result.totalRequests} request(s)`;
150
+ if (providerName === "deepl") {
151
+ console.log(`${head} to DeepL, about ${result.totalChars} characters billed.`);
152
+ }
153
+ else {
154
+ // Rough: ~3.5 chars per token, plus the fixed prompt per request; output about 1.5x the source text.
155
+ const tokensIn = Math.ceil(result.totalPromptChars / 3.5 + result.totalRequests * 450);
156
+ const tokensOut = Math.ceil((result.totalChars / 3.5) * 1.5 + result.totalStrings * 12);
157
+ console.log(`${head} to ${providerName ?? "an LLM provider"}, roughly ${tokensIn} input and ${tokensOut} output tokens (rough guess).`);
158
+ }
159
+ console.log("Nothing was written.");
160
+ }
161
+ }
162
+ /**
163
+ * Resolve --dir, --config and --listing-dir.
164
+ * --config <file>: ext-localize keeps state.json, glossary.json and out/ next to that
165
+ * file, and resolves relative paths inside it from the folder that holds its folder
166
+ * (for the default .localizer/config.json: the extension folder).
167
+ */
168
+ function setup(values) {
169
+ const root = resolve(values.dir ?? ".");
170
+ const configFile = values.config ? resolve(values.config) : undefined;
171
+ if (configFile)
172
+ setLocalizerDir(root, dirname(configFile));
173
+ else
174
+ clearLocalizerDir(root);
175
+ const config = loadConfig(root, configFile);
176
+ const flagDir = values["listing-dir"];
177
+ const abs = flagDir ? resolve(flagDir) : listingDir(root, config.listing?.dir, configBase(root));
178
+ const listing = {
179
+ dir: abs,
180
+ rel: relPath(root, abs),
181
+ explicit: flagDir !== undefined || config.listing?.dir !== undefined,
182
+ /** A listing folder that was asked for must exist: never ignore it silently. */
183
+ require() {
184
+ if (this.explicit && !existsSync(abs)) {
185
+ throw new ConfigError(`listing folder not found: ${abs} (from ${flagDir !== undefined ? "--listing-dir" : `listing.dir "${config.listing?.dir}"`}; ` +
186
+ `a relative listing.dir is resolved from ${configBase(root)})`);
187
+ }
188
+ },
189
+ };
190
+ return { root, config, listing };
191
+ }
192
+ /** Exit codes. See README "Exit codes". */
193
+ export const EXIT_OK = 0;
194
+ export const EXIT_FAILED = 1;
195
+ export const EXIT_USAGE = 2;
196
+ export const EXIT_NO_TARGETS = 3;
197
+ /** The `translate --json` result. See README "translate --json". */
198
+ function translateJson(result, o) {
199
+ return {
200
+ command: "translate",
201
+ target: o.listing ? "listing" : "messages",
202
+ dryRun: o.dryRun,
203
+ provider: o.provider ?? null,
204
+ exitCode: o.exitCode,
205
+ ok: o.exitCode === 0,
206
+ noTargets: o.noTargets,
207
+ stopped: result.stopped ?? null,
208
+ locales: result.locales.map((r) => {
209
+ const count = (reason) => r.plan.translate.filter((t) => t.reason === reason).length;
210
+ return {
211
+ locale: r.locale,
212
+ new: count("new") + count("missing"),
213
+ changed: count("changed"),
214
+ invalid: count("invalid"),
215
+ forced: count("forced"),
216
+ removed: r.plan.remove.length,
217
+ kept: r.plan.keep.length,
218
+ adopted: r.plan.adopt.length,
219
+ manual: r.plan.manual.length,
220
+ translated: r.translated.length,
221
+ failed: r.failed.length,
222
+ requests: r.requests,
223
+ skipped: r.skipped ?? null,
224
+ failedKeys: r.failed,
225
+ written: r.written,
226
+ };
227
+ }),
228
+ totals: {
229
+ strings: result.totalStrings,
230
+ requests: result.totalRequests,
231
+ characters: result.totalChars,
232
+ failed: result.failedCount,
233
+ },
234
+ filesWritten: result.filesWritten,
235
+ mayWrite: o.mayWrite,
236
+ check: o.check,
237
+ };
238
+ }
239
+ async function runTranslate(args) {
240
+ const { values } = parseArgs({
241
+ args,
242
+ options: {
243
+ dir: { type: "string" },
244
+ config: { type: "string" },
245
+ "listing-dir": { type: "string" },
246
+ to: { type: "string" },
247
+ provider: { type: "string" },
248
+ model: { type: "string" },
249
+ effort: { type: "string" },
250
+ formality: { type: "string" },
251
+ glossary: { type: "string" },
252
+ "dry-run": { type: "boolean" },
253
+ force: { type: "boolean" },
254
+ "batch-size": { type: "string" },
255
+ concurrency: { type: "string" },
256
+ listing: { type: "boolean" },
257
+ store: { type: "string" },
258
+ json: { type: "boolean" },
259
+ },
260
+ strict: true,
261
+ });
262
+ const json = values.json ?? false;
263
+ // With --json, stdout carries only the JSON result; progress goes to stderr.
264
+ const say = json ? (line) => console.error(line) : (line) => console.log(line);
265
+ const { root, config, listing } = setup(values);
266
+ if (values.store && !values.listing)
267
+ throw new UsageError(`--store only works with --listing`);
268
+ const stores = values.store ? parseStores(values.store) : config.stores;
269
+ values.provider ??= config.provider;
270
+ values.model ??= config.model;
271
+ values.effort ??= config.effort;
272
+ values.formality ??= config.formality;
273
+ values.to ??= config.to;
274
+ const project = loadProject(root);
275
+ const targets = values.to ? parseTargetLocales(values.to, project.defaultLocale) : undefined;
276
+ const dryRun = values["dry-run"] ?? false;
277
+ if (!dryRun && !values.provider)
278
+ throw new UsageError(`--provider is required (${PROVIDER_NAMES.join(", ")}). Use --dry-run to preview without one.`);
279
+ if (values.provider && !PROVIDER_NAMES.includes(values.provider)) {
280
+ throw new UsageError(`unknown provider "${values.provider}". Use one of: ${PROVIDER_NAMES.join(", ")}`);
281
+ }
282
+ const formality = values.formality;
283
+ if (formality !== undefined && !FORMALITIES.includes(formality)) {
284
+ throw new UsageError(`--formality must be one of ${FORMALITIES.join(", ")}`);
285
+ }
286
+ const provider = dryRun ? undefined : createProvider({ name: values.provider, model: values.model, effort: values.effort });
287
+ // A --glossary flag is relative to the current folder; the config value to the extension folder.
288
+ const glossaryFile = values.glossary ? resolve(values.glossary) : config.glossary ? resolve(configBase(root), config.glossary) : undefined;
289
+ const glossary = loadGlossary(root, glossaryFile);
290
+ const state = loadState(root, project.defaultLocale);
291
+ if (!targets && !dryRun) {
292
+ // Default targets are the existing folders; make that visible.
293
+ say(values.listing ? `No --to given: using the existing locale folders and listing files.` : `No --to given: using the existing locale folders.`);
294
+ }
295
+ const common = {
296
+ provider,
297
+ limits: limitsFor(values.provider),
298
+ dryRun,
299
+ force: values.force,
300
+ glossary,
301
+ formality: formality,
302
+ concurrency: positiveInt(values.concurrency, "--concurrency"),
303
+ batchSize: positiveInt(values["batch-size"], "--batch-size"),
304
+ log: say,
305
+ };
306
+ let result;
307
+ if (values.listing) {
308
+ listing.require();
309
+ const lp = loadListing(project, listing.dir);
310
+ const synced = Object.entries(lp.synced).map(([f, k]) => `${f} <- ${k}`);
311
+ if (synced.length)
312
+ say(`Copied from _locales, not translated (manifest uses __MSG_): ${synced.join(", ")}`);
313
+ result = await runJob(listingJob(project, lp, stores ?? ["chrome"]), state, {
314
+ ...common,
315
+ targets: targets ?? defaultListingTargets(project, lp.dir),
316
+ });
317
+ }
318
+ else {
319
+ result = await translateProject(project, state, { ...common, targets });
320
+ }
321
+ const stateRel = relPath(root, statePath(root));
322
+ const mayWrite = values.listing ? [`${listing.rel}/<locale>.json`, stateRel] : ["_locales/<locale>/messages.json", stateRel];
323
+ const noTargets = result.locales.length === 0;
324
+ let exitCode = noTargets ? EXIT_NO_TARGETS : 0;
325
+ let check = null;
326
+ if (!noTargets && !dryRun) {
327
+ const report = checkProject(root, { stores, listingDir: listing.dir });
328
+ check = { errors: report.errors, warnings: report.warnings, stale: report.stale };
329
+ if (result.failedCount > 0 || result.stopped)
330
+ exitCode = 1;
331
+ }
332
+ if (json) {
333
+ console.log(JSON.stringify(translateJson(result, { listing: !!values.listing, dryRun, provider: values.provider, exitCode, noTargets, mayWrite, check }), null, 2));
334
+ return exitCode;
335
+ }
336
+ if (noTargets) {
337
+ console.log(`No target locales. Use --to (for example --to de,fr or --to all).`);
338
+ return exitCode;
339
+ }
340
+ console.log("");
341
+ printPlan(result, dryRun, values.provider);
342
+ if (dryRun)
343
+ return 0;
344
+ const failures = result.locales.flatMap((r) => r.failed.map((f) => `FAILED ${r.locale} > ${f.key}: ${f.error}`));
345
+ for (const line of failures.slice(0, 20))
346
+ console.log(line);
347
+ if (failures.length > 20)
348
+ console.log(`... and ${failures.length - 20} more failed string(s)`);
349
+ if (result.stopped)
350
+ console.error(`Stopped early: ${result.stopped}`);
351
+ console.log(`State saved to ${statePath(root)}`);
352
+ if (check) {
353
+ console.log(`check: ${check.errors} error(s), ${check.warnings} warning(s), ${check.stale} stale. Run "ext-localize check" for details.`);
354
+ }
355
+ return exitCode;
356
+ }
357
+ function runCheck(args) {
358
+ const { values } = parseArgs({
359
+ args,
360
+ options: {
361
+ dir: { type: "string" },
362
+ config: { type: "string" },
363
+ "listing-dir": { type: "string" },
364
+ json: { type: "boolean" },
365
+ strict: { type: "boolean" },
366
+ store: { type: "string" },
367
+ stale: { type: "string" },
368
+ "listing-only": { type: "boolean" },
369
+ zip: { type: "string" },
370
+ },
371
+ strict: true,
372
+ });
373
+ const { root, config, listing } = setup(values);
374
+ const stores = values.store ? parseStores(values.store) : config.stores;
375
+ const stale = values.stale ?? "warning";
376
+ if (!STALE_MODES.includes(stale))
377
+ throw new UsageError(`--stale must be one of ${STALE_MODES.join(", ")}`);
378
+ listing.require();
379
+ const report = checkProject(root, { stores, listingDir: listing.dir, stale: stale, listingOnly: values["listing-only"] });
380
+ if (values.zip)
381
+ report.issues.push(...zipIssues(values.zip, listing.dir, listing.rel, report.defaultLocale));
382
+ if (values.zip)
383
+ recount(report);
384
+ if (values.json) {
385
+ console.log(JSON.stringify(report, null, 2));
386
+ }
387
+ else {
388
+ for (const issue of report.issues)
389
+ console.log(formatIssue(issue));
390
+ if (report.issues.length)
391
+ console.log("");
392
+ console.log(`${report.locales.length} locale(s) checked: ${report.errors} error(s), ${report.warnings} warning(s), ${report.stale} stale.`);
393
+ const failing = report.errors > 0 || (values.strict && report.warnings > 0);
394
+ console.log(failing ? `FAILED (${report.errors} error(s)${values.strict ? `, ${report.warnings} warning(s) with --strict` : ""})` : "OK");
395
+ }
396
+ const fail = report.errors > 0 || (values.strict && report.warnings > 0);
397
+ return fail ? 1 : 0;
398
+ }
399
+ const list = (s) => (s ?? "").split(",").map((x) => x.trim()).filter(Boolean);
400
+ /** All listing files, with the synced fields of the source filled in from _locales. */
401
+ function loadAllListings(root, listing) {
402
+ listing.require();
403
+ const project = loadProject(root);
404
+ const dir = listing.dir;
405
+ const lp = loadListing(project, dir);
406
+ const listings = readAllListings(dir, project.defaultLocale);
407
+ listings[project.defaultLocale] = lp.source;
408
+ return { listings, defaultLocale: project.defaultLocale };
409
+ }
410
+ async function runPushFirefox(args) {
411
+ const { values } = parseArgs({
412
+ args,
413
+ options: {
414
+ dir: { type: "string" },
415
+ config: { type: "string" },
416
+ "listing-dir": { type: "string" },
417
+ addon: { type: "string" },
418
+ send: { type: "boolean" },
419
+ remove: { type: "string" },
420
+ "default-locale": { type: "string" },
421
+ "extra-locales": { type: "string" },
422
+ host: { type: "string" },
423
+ },
424
+ strict: true,
425
+ });
426
+ const { root, config, listing } = setup(values);
427
+ const addon = values.addon ?? config.firefox?.addon;
428
+ if (!addon)
429
+ throw new UsageError(`--addon <id|slug|guid> is required (or set firefox.addon in .localizer/config.json)`);
430
+ const { listings, defaultLocale } = loadAllListings(root, listing);
431
+ const supported = [...AMO_PROD_LOCALES, ...(config.firefox?.extraLocales ?? []), ...list(values["extra-locales"])];
432
+ const amoDefault = values["default-locale"] ?? config.firefox?.defaultLocale ?? amoDefaultLocale(defaultLocale, supported) ?? "en-US";
433
+ const result = buildPatchBody(listings, { supported, defaultLocale: amoDefault, remove: list(values.remove) });
434
+ const url = addonUrl(values.host ?? config.firefox?.host ?? AMO_HOST, addon);
435
+ const issuer = process.env.AMO_JWT_ISSUER;
436
+ const secret = process.env.AMO_JWT_SECRET;
437
+ console.log(`PATCH ${url}`);
438
+ console.log("Content-Type: application/json");
439
+ console.log(`Authorization: JWT <redacted; AMO_JWT_ISSUER ${issuer ? "set" : "not set"}, AMO_JWT_SECRET ${secret ? "set" : "not set"}>`);
440
+ console.log("");
441
+ console.log(JSON.stringify(result.body, null, 2));
442
+ console.log("");
443
+ console.log(`AMO default locale: ${amoDefault}`);
444
+ console.log("Locale sources: " + (Object.entries(result.sources).map(([a, c]) => `${a}<-${c}`).join(" ") || "(none)"));
445
+ const skipped = result.warnings.filter((w) => w.startsWith("skip "));
446
+ if (skipped.length) {
447
+ console.log(`Cannot be sent to AMO (${skipped.length}):`);
448
+ for (const w of skipped)
449
+ console.log(` ${w.slice(5)}`);
450
+ }
451
+ for (const w of result.warnings.filter((w) => !w.startsWith("skip ")))
452
+ console.error(`warning: ${w}`);
453
+ for (const e of result.errors)
454
+ console.error(`error: ${e}`);
455
+ if (result.errors.length > 0) {
456
+ console.error(`\n${result.errors.length} error(s); not sending.`);
457
+ return 1;
458
+ }
459
+ if (!values.send) {
460
+ console.error(`\nDry run: nothing sent. Add --send (and set AMO_JWT_ISSUER, AMO_JWT_SECRET) to send.`);
461
+ return 0;
462
+ }
463
+ if (!issuer || !secret) {
464
+ console.error(`\nError: --send needs AMO_JWT_ISSUER and AMO_JWT_SECRET in the environment.`);
465
+ return 2;
466
+ }
467
+ const res = await sendPatch(url, result.body, { issuer, secret });
468
+ console.error(`\nHTTP ${res.status}`);
469
+ console.log(res.text);
470
+ return res.ok ? 0 : 1;
471
+ }
472
+ async function runPushChrome(args) {
473
+ const { values } = parseArgs({
474
+ args,
475
+ options: {
476
+ dir: { type: "string" },
477
+ config: { type: "string" },
478
+ "listing-dir": { type: "string" },
479
+ copy: { type: "boolean" },
480
+ mode: { type: "string" },
481
+ out: { type: "string" },
482
+ auto: { type: "boolean" },
483
+ item: { type: "string" },
484
+ save: { type: "boolean" },
485
+ "allow-live": { type: "boolean" },
486
+ browser: { type: "string" },
487
+ profile: { type: "string" },
488
+ login: { type: "boolean" },
489
+ url: { type: "string" },
490
+ headless: { type: "boolean" },
491
+ zip: { type: "string" },
492
+ },
493
+ strict: true,
494
+ });
495
+ const { root, config, listing } = setup(values);
496
+ const mode = (values.mode ?? "fill-all");
497
+ if (mode !== "fill-all" && mode !== "save-each")
498
+ throw new UsageError(`--mode must be fill-all or save-each`);
499
+ if (!values.auto) {
500
+ for (const flag of ["item", "save", "allow-live", "browser", "profile", "login", "url", "headless"]) {
501
+ if (values[flag] !== undefined)
502
+ throw new UsageError(`--${flag} only works with --auto`);
503
+ }
504
+ const { listings } = loadAllListings(root, listing);
505
+ const { descriptions, problems } = chromeDescriptions(listings);
506
+ for (const p of problems)
507
+ console.error(`skip ${p}`);
508
+ if (!Object.keys(descriptions).length) {
509
+ console.error("Error: no description to fill.");
510
+ return 1;
511
+ }
512
+ const dir = outDir(root);
513
+ const file = values.out ? resolve(values.out) : `${dir}/chrome-paste.js`;
514
+ const script = buildPasteScript(descriptions, { mode });
515
+ writeFileSync(file, script);
516
+ const diag = `${dir}/chrome-diagnose.js`;
517
+ writeFileSync(diag, buildDiagnoseScript(Object.keys(descriptions)));
518
+ console.log(`Wrote ${file} (${Object.keys(descriptions).length} language(s): ${Object.keys(descriptions).join(", ")})`);
519
+ console.log(`Wrote ${diag} (read-only check, changes nothing)`);
520
+ if (values.zip) {
521
+ const project = loadProject(root);
522
+ const zi = zipIssues(resolve(values.zip), listing.dir, listing.rel, project.defaultLocale);
523
+ for (const i of zi)
524
+ console.log(`warn ${i.locale}: ${i.message}`);
525
+ if (!zi.length)
526
+ console.log(`The package ${values.zip} has a _locales folder for every listing file.`);
527
+ }
528
+ console.log(`Script size: ${Math.round(Buffer.byteLength(script) / 1024)} KB (pure ASCII; each description carries its length and hash, and the script fills nothing if they do not match).`);
529
+ if (values.copy) {
530
+ const err = copyToClipboard(script);
531
+ if (err) {
532
+ console.error(`Error: could not copy: ${err}`);
533
+ return 1;
534
+ }
535
+ console.log("Copied the script to the clipboard and read it back: it matches the file.");
536
+ }
537
+ console.log(`
538
+ Steps:
539
+ 1. In Chrome, open the Developer Dashboard, your item, then the "Store listing" tab.
540
+ 2. Open the DevTools console: Cmd+Option+J (Mac) or Ctrl+Shift+J.
541
+ 3. Paste the script${values.copy ? " (it is on the clipboard)" : ""} and press Enter.
542
+ The first time, Chrome may ask you to type "allow pasting".
543
+ 4. Wait for the report in the console. Check a few languages.
544
+ 5. Click "Save draft" yourself.${mode === "save-each" ? " (save-each: the script waits for your click after each language.)" : ""}
545
+ Name and summary come from _locales (the manifest); only the description is filled here.
546
+ The script never clicks Submit for review or Publish.`);
547
+ return 0;
548
+ }
549
+ console.error(AUTO_WARNING + "\n");
550
+ const profile = values.profile ?? config.chrome?.profile ?? DEFAULT_PROFILE;
551
+ if (values.login) {
552
+ openLoginBrowser(resolve(profile.replace(/^~(?=\/)/, process.env.HOME ?? "~")));
553
+ console.log(`Opened Chrome on ${profile}. Sign in to Google, open the dashboard once, then quit Chrome (Cmd+Q).`);
554
+ return 0;
555
+ }
556
+ const item = values.item ?? config.chrome?.item;
557
+ if (!item)
558
+ throw new UsageError(`--auto needs --item <itemId> (or chrome.item in .localizer/config.json)`);
559
+ if (!isItemId(item))
560
+ throw new UsageError(`--item must be a 32-letter Chrome item id (letters a-p), not "${item}"`);
561
+ const { listings } = loadAllListings(root, listing);
562
+ const { descriptions, problems } = chromeDescriptions(listings);
563
+ for (const p of problems)
564
+ console.error(`skip ${p}`);
565
+ if (!Object.keys(descriptions).length) {
566
+ console.error("Error: no description to fill.");
567
+ return 1;
568
+ }
569
+ const report = await runAuto(descriptions, {
570
+ item,
571
+ save: values.save,
572
+ allowLive: values["allow-live"],
573
+ testItems: config.chrome?.testItems,
574
+ browser: values.browser ?? config.chrome?.browser,
575
+ profile: resolve(profile.replace(/^~(?=\/)/, process.env.HOME ?? "~")),
576
+ publisher: config.chrome?.publisher,
577
+ url: values.url,
578
+ headless: values.headless,
579
+ log: (line) => console.log(line),
580
+ });
581
+ const file = writeAutoReport(outDir(root), report);
582
+ const f = report.fill;
583
+ if (f) {
584
+ for (const u of f.unmatched)
585
+ console.log(`not in the dashboard language list: ${u.locale} (${u.dashboardCode})`);
586
+ for (const e of f.errors)
587
+ console.log(`error ${e.locale}: ${e.error}`);
588
+ if (f.hint)
589
+ console.log(f.hint);
590
+ }
591
+ for (const r of report.afterReload?.rows.filter((r) => !r.ok) ?? [])
592
+ console.log(`after reload, ${r.locale} differs: ${r.error ?? `${r.gotLength} vs ${r.wantLength} chars`}`);
593
+ if (report.error)
594
+ console.error(`Error: ${report.error}`);
595
+ console.log(`Report: ${file}`);
596
+ const ok = !report.error && report.fillOk && (!values.save || report.afterReload?.ok === true);
597
+ return ok ? 0 : 1;
598
+ }
599
+ function runPushEdge(args) {
600
+ const { values } = parseArgs({
601
+ args,
602
+ options: { dir: { type: "string" }, config: { type: "string" }, "listing-dir": { type: "string" }, print: { type: "boolean" } },
603
+ strict: true,
604
+ });
605
+ const { root, config, listing } = setup(values);
606
+ const { listings } = loadAllListings(root, listing);
607
+ const dir = `${outDir(root)}/edge`;
608
+ const entries = writeEdgeFiles(listings, dir);
609
+ if (values.print)
610
+ for (const e of entries)
611
+ if (e.file)
612
+ console.log(edgeBlock(e.locale, listings[e.locale] ?? {}));
613
+ for (const e of entries)
614
+ console.log(`${e.locale.padEnd(7)} ${String(e.length).padStart(6)} chars ${e.problem ?? "ok"}`);
615
+ console.log(`
616
+ Wrote ${entries.filter((e) => e.file).length} file(s) to ${dir}
617
+ Edge has no API for listing text. In Partner Center, open your extension, "Store listings",
618
+ pick each language and paste its Description. Name and short description come from the
619
+ manifest (_locales), so they are not in these files.`);
620
+ return entries.some((e) => e.problem) ? 1 : 0;
621
+ }
622
+ function runListing(args) {
623
+ const [sub1, ...rest] = args;
624
+ if (sub1 !== "import")
625
+ throw new UsageError(`listing needs a subcommand: import`);
626
+ const { values, positionals } = parseArgs({
627
+ args: rest,
628
+ options: {
629
+ dir: { type: "string" },
630
+ config: { type: "string" },
631
+ "listing-dir": { type: "string" },
632
+ force: { type: "boolean" },
633
+ },
634
+ allowPositionals: true,
635
+ strict: true,
636
+ });
637
+ const pattern = positionals[0];
638
+ if (!pattern || positionals.length > 1) {
639
+ throw new UsageError(`usage: ext-localize listing import <folder | "path/{locale}.txt"> [--force]`);
640
+ }
641
+ const { root, listing } = setup(values);
642
+ const project = loadProject(root);
643
+ const result = importDescriptions(project, listing.dir, resolve(pattern), { force: values.force });
644
+ for (const r of result)
645
+ console.log(`${r.locale.padEnd(7)} ${r.action.padEnd(8)} ${r.note ?? ""}`.trimEnd());
646
+ const written = result.filter((r) => r.action === "written").length;
647
+ console.log(`\nWrote ${written} listing file(s) to ${listing.rel}. Run "ext-localize check" to validate them.`);
648
+ return 0;
649
+ }
650
+ async function runPush(args) {
651
+ const [store, ...rest] = args;
652
+ switch (store) {
653
+ case "firefox":
654
+ return runPushFirefox(rest);
655
+ case "chrome":
656
+ return runPushChrome(rest);
657
+ case "edge":
658
+ return runPushEdge(rest);
659
+ default:
660
+ throw new UsageError(`push needs a store: firefox, chrome or edge`);
661
+ }
662
+ }
663
+ export async function main(argv) {
664
+ const [command, ...rest] = argv;
665
+ try {
666
+ switch (command) {
667
+ case "translate":
668
+ return await runTranslate(rest);
669
+ case "check":
670
+ return runCheck(rest);
671
+ case "listing":
672
+ return runListing(rest);
673
+ case "push":
674
+ return await runPush(rest);
675
+ case "-v":
676
+ case "--version":
677
+ console.log(version());
678
+ return 0;
679
+ case undefined:
680
+ case "-h":
681
+ case "--help":
682
+ case "help":
683
+ console.log(HELP);
684
+ return 0;
685
+ default:
686
+ console.error(`Unknown command "${command}".\n`);
687
+ console.error(HELP);
688
+ return 2;
689
+ }
690
+ }
691
+ catch (e) {
692
+ const err = e;
693
+ const usage = e instanceof UsageError || e instanceof ProjectError || e instanceof ListingError || e instanceof ConfigError || !!err.code?.startsWith("ERR_PARSE_ARGS");
694
+ const code = usage ? EXIT_USAGE : EXIT_FAILED;
695
+ if (argv.includes("--json")) {
696
+ // Keep stdout machine-readable even on errors.
697
+ console.log(JSON.stringify({ command: command ?? null, exitCode: code, ok: false, error: err.message }, null, 2));
698
+ }
699
+ if (e instanceof UsageError || err.code?.startsWith("ERR_PARSE_ARGS")) {
700
+ console.error(`Error: ${err.message}\nRun "ext-localize --help" for usage.`);
701
+ }
702
+ else {
703
+ console.error(`Error: ${err.message}`);
704
+ }
705
+ return code;
706
+ }
707
+ }
708
+ // npm installs the bin as a symlink, so compare real paths.
709
+ function isMainModule() {
710
+ try {
711
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
712
+ }
713
+ catch {
714
+ return false;
715
+ }
716
+ }
717
+ const isMain = isMainModule();
718
+ if (isMain) {
719
+ main(process.argv.slice(2)).then((code) => {
720
+ process.exitCode = code;
721
+ });
722
+ }