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,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
+ }
@@ -0,0 +1,147 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { codePoints } from "../listing.js";
6
+ /**
7
+ * Chrome Web Store listing delivery.
8
+ *
9
+ * Chrome has no API for listing text. Name and summary come from the manifest
10
+ * (_locales). Only the "Detailed description" is typed per language in the
11
+ * dashboard. Default delivery: one script the developer pastes into DevTools on
12
+ * the Store listing tab; it fills every language, and the developer clicks
13
+ * "Save draft". The script never clicks Submit or Publish.
14
+ */
15
+ /** Dashboard textarea maxlength (seen on the real dashboard; not in Google docs). */
16
+ export const CHROME_DESCRIPTION_MAX = 16000;
17
+ export const DASHBOARD_URL = "https://chrome.google.com/webstore/devconsole/";
18
+ /** fill-core.js ships in assets/ next to src/ and dist/. */
19
+ export function fillCorePath() {
20
+ const here = dirname(fileURLToPath(import.meta.url));
21
+ return join(here, "..", "..", "assets", "fill-core.js");
22
+ }
23
+ export function readFillCore() {
24
+ return readFileSync(fillCorePath(), "utf8");
25
+ }
26
+ /** Pick the descriptions to fill; report the ones that cannot be used. */
27
+ export function chromeDescriptions(listings) {
28
+ const descriptions = {};
29
+ const problems = [];
30
+ for (const locale of Object.keys(listings).sort()) {
31
+ const d = listings[locale]?.description;
32
+ if (d === undefined || d.trim() === "") {
33
+ problems.push(`${locale}: no description`);
34
+ continue;
35
+ }
36
+ if (codePoints(d) > CHROME_DESCRIPTION_MAX) {
37
+ problems.push(`${locale}: description is ${codePoints(d)} characters; the dashboard limit is ${CHROME_DESCRIPTION_MAX}`);
38
+ continue;
39
+ }
40
+ descriptions[locale] = { description: d };
41
+ }
42
+ return { descriptions, problems };
43
+ }
44
+ /**
45
+ * Build the paste script. Plain concatenation (no templates over fill-core,
46
+ * which contains "$" and backticks of its own).
47
+ */
48
+ export function buildPasteScript(descriptions, opts = {}) {
49
+ const mode = opts.mode ?? "fill-all";
50
+ const save = mode === "save-each" ? "wait" : "none";
51
+ const core = opts.core ?? readFillCore();
52
+ const locales = Object.keys(descriptions);
53
+ return [
54
+ "// ext-localize: paste into the DevTools console on the Chrome Web Store \"Store listing\" tab.",
55
+ `// Fills the detailed description for ${locales.length} language(s): ${locales.join(", ")}.`,
56
+ "// It never clicks Submit for review or Publish. Check the text, then click \"Save draft\" yourself.",
57
+ `// mode=${mode}`,
58
+ "(async () => {",
59
+ core,
60
+ "const LISTINGS = " + JSON.stringify(descriptions, null, 2) + ";",
61
+ "window.__listingFillReport = await globalThis.ListingFill.run(LISTINGS, { mode: " +
62
+ JSON.stringify(mode) +
63
+ ", save: " +
64
+ JSON.stringify(save) +
65
+ " });",
66
+ "})();",
67
+ "",
68
+ ].join("\n");
69
+ }
70
+ /** Read-only script: finds the elements and lists the dashboard languages. Changes nothing. */
71
+ export function buildDiagnoseScript(locales, opts = {}) {
72
+ const core = opts.core ?? readFillCore();
73
+ return [
74
+ "// ext-localize: DIAGNOSE (read-only). Paste on the Store listing tab. Changes nothing, saves nothing.",
75
+ "(async () => {",
76
+ core,
77
+ "const L = globalThis.ListingFill, out = { url: location.href, version: L.VERSION };",
78
+ "const tryIt = (k, f) => { try { out[k] = f(); } catch (e) { out[k] = 'ERROR: ' + e.message; } };",
79
+ "tryIt('textarea', () => { const t = L.findTextarea(); return { foundBy: t.how, maxlength: t.el.getAttribute('maxlength'), length: t.el.value.length }; });",
80
+ "try { out.languages = await L.listDashboardLanguages(); } catch (e) { out.languages = 'ERROR: ' + e.message; }",
81
+ "out.localeFiles = " + JSON.stringify(locales) + ".map((l) => ({ locale: l, dashboardCode: L.toDashboardCode(l) }));",
82
+ "console.log('[listing-fill] DIAGNOSE', JSON.stringify(out, null, 2));",
83
+ "window.__listingFillDiagnose = out;",
84
+ "})();",
85
+ "",
86
+ ].join("\n");
87
+ }
88
+ /** Output folder for generated files. It gets its own .gitignore. */
89
+ export function outDir(root) {
90
+ const dir = join(root, ".localizer", "out");
91
+ mkdirSync(dir, { recursive: true });
92
+ const gi = join(dir, ".gitignore");
93
+ if (!existsSync(gi))
94
+ writeFileSync(gi, "# Generated by ext-localize. Not meant for git.\n*\n");
95
+ return dir;
96
+ }
97
+ /** Copy text to the macOS clipboard. Returns an error message, or null on success. */
98
+ export function copyToClipboard(text) {
99
+ if (process.platform !== "darwin")
100
+ return "copying is only supported on macOS (pbcopy); open the file instead";
101
+ const r = spawnSync("pbcopy", { input: text });
102
+ if (r.error)
103
+ return r.error.message;
104
+ return r.status === 0 ? null : `pbcopy exited with ${r.status}`;
105
+ }
106
+ // ---------------------------------------------------------------------------
107
+ // Guards shared with --auto
108
+ // ---------------------------------------------------------------------------
109
+ const DASHBOARD_HOSTS = new Set(["chrome.google.com", "chromewebstore.google.com"]);
110
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
111
+ /**
112
+ * Item id of a dashboard URL, or null. Only the dashboard hosts count (and
113
+ * local pages, used by the tests with a mock dashboard).
114
+ * Example: https://chrome.google.com/webstore/devconsole/<publisher>/<item>/edit
115
+ */
116
+ export function itemFromUrl(url) {
117
+ let u;
118
+ try {
119
+ u = new URL(url);
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ if (!DASHBOARD_HOSTS.has(u.hostname) && !LOCAL_HOSTS.has(u.hostname))
125
+ return null;
126
+ const m = /\/devconsole\/[^/]+\/([a-p]{32})(?:\/|$)/.exec(u.pathname);
127
+ return m ? m[1] : null;
128
+ }
129
+ export function isItemId(id) {
130
+ return /^[a-p]{32}$/.test(id);
131
+ }
132
+ /**
133
+ * Decide whether --auto may click "Save draft".
134
+ * - --item is always required, and the open tab must be that item.
135
+ * - Saving is allowed on items listed in chrome.testItems (config). Any other
136
+ * item may be live, so it also needs --allow-live.
137
+ */
138
+ export function checkSaveAllowed(tabItem, a) {
139
+ if (!a.item)
140
+ throw new Error("Refusing: pass --item <itemId> so only the item you named is touched.");
141
+ if (tabItem !== a.item)
142
+ throw new Error(`Refusing: the open tab is item ${tabItem ?? "(none)"}, not --item ${a.item}.`);
143
+ if (a.save && !(a.testItems ?? []).includes(a.item) && !a.allowLive) {
144
+ throw new Error(`Refusing to save: ${a.item} is not in chrome.testItems in .localizer/config.json, so it may be a live item. ` +
145
+ `Use a test item, or pass --allow-live after you decide to.`);
146
+ }
147
+ }
@@ -0,0 +1,43 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { EDGE_DESCRIPTION_MIN, STORE_LIMITS, codePoints } from "../listing.js";
4
+ /**
5
+ * Microsoft Edge Add-ons: there is no API for listing text. The Edge Add-ons
6
+ * REST API only uploads and publishes packages; the docs say metadata such as
7
+ * the description must be edited in Partner Center.
8
+ *
9
+ * In Partner Center the extension name and short description are read from the
10
+ * package manifest (_locales). Only the Description (250 to 10,000 characters)
11
+ * and optional search terms are typed per language. So this command writes one
12
+ * text file per locale with the description, ready to copy.
13
+ * Source: https://learn.microsoft.com/en-us/microsoft-edge/extensions/publish/publish-extension
14
+ */
15
+ export const EDGE_DESCRIPTION_MAX = STORE_LIMITS.edge.description;
16
+ /** Write <dir>/<locale>.txt per listing; return what was written and what has problems. */
17
+ export function writeEdgeFiles(listings, dir) {
18
+ mkdirSync(dir, { recursive: true });
19
+ const out = [];
20
+ for (const locale of Object.keys(listings).sort()) {
21
+ const d = listings[locale]?.description ?? "";
22
+ const length = codePoints(d);
23
+ const entry = { locale, length };
24
+ if (d.trim() === "")
25
+ entry.problem = "no description";
26
+ else if (length < EDGE_DESCRIPTION_MIN)
27
+ entry.problem = `too short: Partner Center needs at least ${EDGE_DESCRIPTION_MIN} characters`;
28
+ else if (length > EDGE_DESCRIPTION_MAX)
29
+ entry.problem = `too long: Partner Center allows at most ${EDGE_DESCRIPTION_MAX} characters`;
30
+ if (d.trim() !== "") {
31
+ const file = join(dir, `${locale}.txt`);
32
+ writeFileSync(file, d.endsWith("\n") ? d : d + "\n");
33
+ entry.file = file;
34
+ }
35
+ out.push(entry);
36
+ }
37
+ return out;
38
+ }
39
+ /** Copy-ready block for one locale. */
40
+ export function edgeBlock(locale, listing) {
41
+ const line = "=".repeat(60);
42
+ return `${line}\n${locale} - Description (${codePoints(listing.description ?? "")} characters)\n${line}\n${listing.description ?? ""}\n`;
43
+ }
@@ -0,0 +1,235 @@
1
+ // Firefox Add-ons (AMO): push the translated listing with one PATCH.
2
+ // Ported from spikes/amo-push (locales.ts, payload.ts, jwt.ts); see its REPORT.md for sources.
3
+ //
4
+ // - PATCH /api/v5/addons/addon/<id|slug|guid>/ with {name, summary, description} as locale -> text maps.
5
+ // Locales not sent are left as they are; null deletes a locale.
6
+ // - Auth: "Authorization: JWT <token>", HS256, iss = API key, exp at most 5 minutes after iat.
7
+ // https://addons-server.readthedocs.io/en/latest/topics/api/auth.html
8
+ import { createHmac, randomUUID } from 'node:crypto';
9
+ import { LISTING_FIELDS } from '../listing.js';
10
+ // Chrome -> AMO locale mapping.
11
+ //
12
+ // Sources (checked 2026-11-16):
13
+ // - Chrome Web Store locales: https://developer.chrome.com/docs/extensions/reference/api/i18n#locales
14
+ // - AMO locales: mozilla/addons-server src/olympia/core/languages.py (PROD_LANGUAGES),
15
+ // used as AMO_LANGUAGES by src/olympia/conf/prod/settings.py.
16
+ // Commit e9274a547adb34545aee8fc8fa53aa27394d8a40 (2026-11-13).
17
+ // A PATCH with a locale key not in this list is rejected by
18
+ // TranslationSerializerField ("The language code ... is invalid.").
19
+ // Mozilla changes this list when translation completeness changes,
20
+ // so callers can pass their own list.
21
+ /** Locales AMO production accepts in translated fields (PROD_LANGUAGES, 44 codes). */
22
+ export const AMO_PROD_LOCALES = [
23
+ 'cs', 'de', 'dsb', 'el', 'en-CA', 'en-GB', 'en-US', 'es-AR', 'es-CL', 'es-ES',
24
+ 'es-MX', 'fa', 'fi', 'fr', 'fur', 'fy-NL', 'he', 'hr', 'hsb', 'hu', 'ia', 'it',
25
+ 'ja', 'ka', 'kab', 'ko', 'nb-NO', 'nl', 'nn-NO', 'pl', 'pt-BR', 'pt-PT', 'ro',
26
+ 'ru', 'sk', 'sl', 'sq', 'sr', 'sv-SE', 'tr', 'uk', 'vi', 'zh-CN', 'zh-TW',
27
+ ];
28
+ /**
29
+ * Codes that cannot be mapped by replacing "_" with "-".
30
+ * "addons-server" = SHORTER_LANGUAGES in src/olympia/lib/settings_base.py.
31
+ * "our choice" = a decision of this project, not from Mozilla.
32
+ */
33
+ const ALIASES = {
34
+ en: { amo: ['en-US'], rule: 'alias', source: 'addons-server' },
35
+ es: { amo: ['es-ES'], rule: 'alias', source: 'addons-server' },
36
+ ga: { amo: ['ga-IE'], rule: 'alias', source: 'addons-server' },
37
+ pt: { amo: ['pt-PT'], rule: 'alias', source: 'addons-server' },
38
+ sv: { amo: ['sv-SE'], rule: 'alias', source: 'addons-server' },
39
+ zh: { amo: ['zh-CN'], rule: 'alias', source: 'addons-server' },
40
+ // Chrome "no" is Norwegian Bokmal in practice.
41
+ no: { amo: ['nb-NO'], rule: 'alias', source: 'our choice' },
42
+ // AMO falls back to the add-on default locale, not to another Spanish,
43
+ // so we copy Latin American Spanish to every Latin American locale AMO has.
44
+ es_419: { amo: ['es-AR', 'es-CL', 'es-MX'], rule: 'fan-out', source: 'our choice' },
45
+ };
46
+ /** Why some Chrome codes are skipped. Shown to the user as a warning. */
47
+ const SKIP_NOTES = {
48
+ fil: 'AMO knows "tl" (Tagalog) but it is not enabled on production. Not folded into another locale.',
49
+ en_AU: 'AMO knows "en-AU" but it is not enabled on production. Not folded into en-US/en-GB.',
50
+ };
51
+ /**
52
+ * Map one Chrome locale code (e.g. "pt_BR") to AMO locale codes (e.g. ["pt-BR"]).
53
+ * `supported` is the list of AMO locales the target server accepts.
54
+ */
55
+ export function mapChromeLocale(chrome, supported = AMO_PROD_LOCALES) {
56
+ const byLower = new Map(supported.map((l) => [l.toLowerCase(), l]));
57
+ const alias = ALIASES[chrome];
58
+ if (alias) {
59
+ // Partial fan-out is fine: send to the targets the server accepts.
60
+ const amo = alias.amo
61
+ .map((l) => byLower.get(l.toLowerCase()))
62
+ .filter((l) => l !== undefined);
63
+ if (amo.length === 0) {
64
+ return { ok: false, chrome, reason: `maps to ${alias.amo.join(', ')}, which AMO does not accept` };
65
+ }
66
+ return { ok: true, chrome, amo, rule: alias.rule, source: alias.source, priority: 1 };
67
+ }
68
+ const candidate = chrome.replace(/_/g, '-').toLowerCase();
69
+ const canonical = byLower.get(candidate);
70
+ if (canonical) {
71
+ return { ok: true, chrome, amo: [canonical], rule: 'direct', source: 'same code', priority: 2 };
72
+ }
73
+ const reason = SKIP_NOTES[chrome] ?? `AMO does not accept "${chrome.replace(/_/g, '-')}"`;
74
+ return { ok: false, chrome, reason };
75
+ }
76
+ /**
77
+ * Resolve a locale given on the command line (for --remove).
78
+ * Accepts an AMO code ("pt-BR") or a Chrome code ("pt_BR").
79
+ */
80
+ export function resolveLocaleArg(arg, supported = AMO_PROD_LOCALES) {
81
+ const exact = supported.find((l) => l.toLowerCase() === arg.toLowerCase());
82
+ if (exact)
83
+ return [exact];
84
+ const mapped = mapChromeLocale(arg, supported);
85
+ return mapped.ok ? mapped.amo : [];
86
+ }
87
+ // Build the JSON body for PATCH /api/v5/addons/addon/<id>/
88
+ //
89
+ // Translated field format (addons-server docs, "Translated Fields"):
90
+ // { "name": { "en-US": "...", "de": "..." } }
91
+ // Locales not in the object are left as they are. A null value deletes that locale.
92
+ // The add-on default locale value cannot be deleted while other locales exist.
93
+ const FIELDS = LISTING_FIELDS;
94
+ /**
95
+ * Max lengths from the Addon model in addons-server (src/olympia/addons/models.py):
96
+ * name = TranslatedField(max_length=50)
97
+ * summary = NoURLsField(max_length=250)
98
+ * description = PurifiedMarkdownField(max_length=15000)
99
+ * The API returns 400 above these (addons-server tests test_fields_max_length,
100
+ * test_set_data_too_long_other_textfields). We check them here too, so a bad file
101
+ * fails before any request.
102
+ */
103
+ export const AMO_LIMITS = { name: 50, summary: 250, description: 15000 };
104
+ /** Length in Unicode code points. Python (the AMO server) counts this way, not in UTF-16 units. */
105
+ export function codePointLength(s) {
106
+ return [...s].length;
107
+ }
108
+ export function buildPatchBody(listings, options = {}) {
109
+ const supported = options.supported ?? AMO_PROD_LOCALES;
110
+ const defaultLocale = options.defaultLocale ?? 'en-US';
111
+ const errors = [];
112
+ const warnings = [];
113
+ // 1. Pick the Chrome file for each AMO locale. A more specific file wins
114
+ // (e.g. en_US beats en for en-US). Equal priority is an error.
115
+ const chosen = new Map();
116
+ for (const chrome of Object.keys(listings).sort()) {
117
+ const m = mapChromeLocale(chrome, supported);
118
+ if (!m.ok) {
119
+ warnings.push(`skip ${chrome}: ${m.reason}`);
120
+ continue;
121
+ }
122
+ for (const amo of m.amo) {
123
+ const prev = chosen.get(amo);
124
+ if (!prev || m.priority > prev.priority) {
125
+ if (prev)
126
+ warnings.push(`${amo}: using ${chrome}, not the less specific ${prev.chrome}`);
127
+ chosen.set(amo, { chrome, priority: m.priority });
128
+ }
129
+ else if (m.priority === prev.priority) {
130
+ errors.push(`${chrome} and ${prev.chrome} both map to ${amo}; keep only one`);
131
+ }
132
+ else {
133
+ warnings.push(`${amo}: using ${prev.chrome}, not the less specific ${chrome}`);
134
+ }
135
+ }
136
+ }
137
+ // 2. Check each used file once, then fill the body.
138
+ const valid = new Map();
139
+ for (const chrome of new Set([...chosen.values()].map((c) => c.chrome))) {
140
+ const listing = listings[chrome] ?? {};
141
+ const ok = {};
142
+ for (const field of FIELDS) {
143
+ const value = listing[field];
144
+ if (value === undefined)
145
+ continue;
146
+ if (typeof value !== 'string') {
147
+ errors.push(`${chrome}.${field}: must be a string`);
148
+ continue;
149
+ }
150
+ if (value.trim() === '') {
151
+ errors.push(`${chrome}.${field}: empty; remove the key to leave it unchanged`);
152
+ continue;
153
+ }
154
+ const len = codePointLength(value);
155
+ if (len > AMO_LIMITS[field]) {
156
+ errors.push(`${chrome}.${field}: ${len} characters, limit is ${AMO_LIMITS[field]}`);
157
+ }
158
+ ok[field] = value;
159
+ }
160
+ valid.set(chrome, ok);
161
+ }
162
+ const body = {};
163
+ const sources = {};
164
+ for (const [amo, { chrome }] of [...chosen].sort(([a], [b]) => a.localeCompare(b))) {
165
+ sources[amo] = chrome;
166
+ const listing = valid.get(chrome);
167
+ for (const field of FIELDS) {
168
+ const value = listing[field];
169
+ if (value !== undefined)
170
+ (body[field] ??= {})[amo] = value;
171
+ }
172
+ }
173
+ // 3. Deletions.
174
+ for (const arg of options.remove ?? []) {
175
+ const locales = resolveLocaleArg(arg, supported);
176
+ if (locales.length === 0) {
177
+ errors.push(`--remove ${arg}: not a locale AMO accepts (the API rejects unknown locale keys, even with null)`);
178
+ continue;
179
+ }
180
+ for (const amo of locales) {
181
+ if (amo.toLowerCase() === defaultLocale.toLowerCase()) {
182
+ errors.push(`--remove ${arg}: ${amo} is the default locale; AMO does not allow deleting it`);
183
+ continue;
184
+ }
185
+ if (chosen.has(amo)) {
186
+ errors.push(`--remove ${arg}: ${amo} also has a listing file (${chosen.get(amo).chrome})`);
187
+ continue;
188
+ }
189
+ for (const field of FIELDS)
190
+ (body[field] ??= {})[amo] = null;
191
+ }
192
+ }
193
+ if (body.name || body.summary) {
194
+ warnings.push('name/summary changes start an AMO content review (addons-server AddonSerializer.update)');
195
+ }
196
+ if (Object.keys(body).length === 0) {
197
+ errors.push('nothing to send');
198
+ }
199
+ return { body, errors, warnings, sources };
200
+ }
201
+ // ---- JWT ----
202
+ function b64url(input) {
203
+ return Buffer.from(input).toString('base64url');
204
+ }
205
+ export function signAmoJwt(issuer, secret, opts = {}) {
206
+ const iat = Math.floor((opts.now ?? Date.now()) / 1000);
207
+ const ttl = Math.min(opts.ttlSeconds ?? 60, 300);
208
+ const header = { alg: 'HS256', typ: 'JWT' };
209
+ const payload = { iss: issuer, jti: opts.jti ?? randomUUID(), iat, exp: iat + ttl };
210
+ const unsigned = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
211
+ const sig = createHmac('sha256', secret).update(unsigned).digest('base64url');
212
+ return `${unsigned}.${sig}`;
213
+ }
214
+ export const AMO_HOST = 'https://addons.mozilla.org';
215
+ export function addonUrl(host, addon) {
216
+ return `${host.replace(/\/+$/, '')}/api/v5/addons/addon/${encodeURIComponent(addon)}/`;
217
+ }
218
+ /** AMO code for the add-on default locale, from the Chrome default_locale (en -> en-US). */
219
+ export function amoDefaultLocale(chromeDefault, supported = AMO_PROD_LOCALES) {
220
+ const m = mapChromeLocale(chromeDefault, supported);
221
+ return m.ok ? (m.amo[0] ?? null) : null;
222
+ }
223
+ /** Send the PATCH. Only called with an explicit --send and both env vars set. */
224
+ export async function sendPatch(url, body, creds, fetchImpl = fetch) {
225
+ const res = await fetchImpl(url, {
226
+ method: 'PATCH',
227
+ headers: {
228
+ Authorization: `JWT ${signAmoJwt(creds.issuer, creds.secret)}`,
229
+ 'Content-Type': 'application/json',
230
+ Accept: 'application/json',
231
+ },
232
+ body: JSON.stringify(body),
233
+ });
234
+ return { status: res.status, ok: res.ok, text: await res.text() };
235
+ }