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.
@@ -0,0 +1,398 @@
1
+ /*
2
+ * fill-core.js - fills the "Detailed description" of every language on the
3
+ * Chrome Web Store dashboard "Store listing" tab. Used by `ext-localize push chrome`
4
+ * (paste script) and `ext-localize push chrome --auto` (DevTools Protocol).
5
+ *
6
+ * Copied from spikes/chrome-listing-delivery/shared/fill-core.js (the fixed version:
7
+ * the language dropdown is matched by data-value, and the trigger text is checked with
8
+ * "contains", because the real dashboard adds icon text like "arrow_drop_down").
9
+ *
10
+ * Plain browser JavaScript, no build step. It sets `globalThis.ListingFill`.
11
+ *
12
+ * Rules it follows:
13
+ * - Find elements by role/label first, CSS selectors second.
14
+ * - Fail loudly when a lookup finds 0 or more than 1 element.
15
+ * - Read the language list from the live dropdown; report locales it cannot match.
16
+ * Only two code rewrites: "_" -> "-" and "he" -> "iw".
17
+ * - Wait for the page to settle after a language switch before writing.
18
+ * - After filling, walk all languages again and compare what the page holds to the file.
19
+ * - Never clicks "Submit for review" / "Publish". "Save draft" only if the caller asks.
20
+ */
21
+ (function (root) {
22
+ 'use strict';
23
+
24
+ const VERSION = '0.2.1';
25
+ const MAX_LEN = 16000; // dashboard limit for the detailed description (from LocalePack's selector; not in Google docs)
26
+
27
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
28
+ const norm = (s) => String(s == null ? '' : s).replace(/\r\n/g, '\n');
29
+ const clean = (s) => String(s || '').replace(/\s+/g, ' ').trim();
30
+
31
+ // Chrome _locales code -> dashboard code. pt_BR -> pt-BR, he -> iw.
32
+ function toDashboardCode(locale) {
33
+ let c = String(locale).replace(/_/g, '-');
34
+ if (c === 'he' || c.startsWith('he-')) c = 'iw' + c.slice(2);
35
+ return c;
36
+ }
37
+
38
+ function isVisible(el) {
39
+ if (!el || !el.isConnected) return false;
40
+ const r = el.getBoundingClientRect();
41
+ if (r.width === 0 && r.height === 0) return false;
42
+ const cs = getComputedStyle(el);
43
+ return cs.visibility !== 'hidden' && cs.display !== 'none';
44
+ }
45
+
46
+ // Small accessible-name helper (not the full spec; enough for labels/aria).
47
+ function accName(el) {
48
+ if (!el) return '';
49
+ const al = el.getAttribute('aria-label');
50
+ if (al) return clean(al);
51
+ const lb = el.getAttribute('aria-labelledby');
52
+ if (lb) {
53
+ const t = lb.split(/\s+/).map((id) => document.getElementById(id)).filter(Boolean).map((n) => n.textContent).join(' ');
54
+ if (clean(t)) return clean(t);
55
+ }
56
+ if (el.id) {
57
+ const lab = document.querySelector('label[for="' + CSS.escape(el.id) + '"]');
58
+ if (lab) return clean(lab.textContent);
59
+ }
60
+ const wrap = el.closest('label');
61
+ if (wrap) return clean(wrap.textContent);
62
+ return '';
63
+ }
64
+
65
+ // Try strategies in order. The first strategy that finds anything wins.
66
+ // 0 matches overall, or >1 match in the winning strategy -> throw.
67
+ function findOne(what, strategies) {
68
+ for (const [how, fn] of strategies) {
69
+ let found;
70
+ try { found = Array.from(new Set(fn())).filter(isVisible); } catch (e) { found = []; }
71
+ if (found.length === 1) return { el: found[0], how };
72
+ if (found.length > 1) throw new Error('More than one match for ' + what + ' (strategy "' + how + '", ' + found.length + ' matches). Selectors need an update.');
73
+ }
74
+ throw new Error('Not found: ' + what + '. The dashboard markup may have changed.');
75
+ }
76
+ function tryFindOne(what, strategies) {
77
+ try { return findOne(what, strategies); } catch (e) { return null; }
78
+ }
79
+
80
+ const $$ = (sel, r) => Array.from((r || document).querySelectorAll(sel));
81
+
82
+ function findTrigger() {
83
+ return findOne('language dropdown ("Current editing language")', [
84
+ ['role=combobox + label', () => $$('[role=combobox]').filter((e) => /editing language|^language$/i.test(accName(e)))],
85
+ ['text label + button', () => {
86
+ const labels = $$('label, span, div, p').filter((e) => e.children.length === 0 && /^current editing language$/i.test(clean(e.textContent)));
87
+ const out = [];
88
+ for (const lab of labels) {
89
+ const box = lab.parentElement;
90
+ if (box) out.push(...$$('[role=button], [role=combobox], [aria-haspopup], button, select', box));
91
+ }
92
+ return out;
93
+ }],
94
+ ]);
95
+ }
96
+
97
+ function findList() {
98
+ return tryFindOne('language list', [
99
+ ['role=listbox named Language', () => $$('[role=listbox]').filter((e) => /^language$/i.test(accName(e)))],
100
+ ["css ul[aria-label='Language']", () => $$("ul[aria-label='Language']")],
101
+ ]);
102
+ }
103
+
104
+ function findTextarea() {
105
+ return findOne('description textarea', [
106
+ ['textarea labelled "description"', () => $$('textarea').filter((e) => /description/i.test(accName(e)))],
107
+ ["css textarea[maxlength='16000']", () => $$("textarea[maxlength='16000']")],
108
+ ]);
109
+ }
110
+
111
+ function findSaveDraft() {
112
+ const r = findOne('"Save draft" button', [
113
+ ['button named Save draft', () => $$('button, [role=button]').filter((e) => /^save draft$/i.test(clean(e.textContent) || accName(e)))],
114
+ ]);
115
+ if (/submit|publish|review/i.test(clean(r.el.textContent))) throw new Error('Refusing: save button text looks like submit/publish.');
116
+ return r.el;
117
+ }
118
+
119
+ // Full pointer/mouse sequence. Some UI kits open on mousedown, others on click.
120
+ function realClick(el) {
121
+ const o = { bubbles: true, cancelable: true, view: window, button: 0 };
122
+ if (typeof PointerEvent === 'function') el.dispatchEvent(new PointerEvent('pointerdown', o));
123
+ el.dispatchEvent(new MouseEvent('mousedown', o));
124
+ if (typeof PointerEvent === 'function') el.dispatchEvent(new PointerEvent('pointerup', o));
125
+ el.dispatchEvent(new MouseEvent('mouseup', o));
126
+ el.dispatchEvent(new MouseEvent('click', o));
127
+ }
128
+
129
+ async function waitFor(fn, what, timeout) {
130
+ const end = Date.now() + (timeout || 8000);
131
+ for (;;) {
132
+ let v;
133
+ try { v = fn(); } catch (e) { v = null; }
134
+ if (v) return v;
135
+ if (Date.now() > end) throw new Error('Timed out waiting for ' + what);
136
+ await sleep(50);
137
+ }
138
+ }
139
+
140
+ // Resolve when the DOM has had no mutations for `quietMs`.
141
+ function waitQuiet(quietMs, timeout) {
142
+ quietMs = quietMs || 250;
143
+ return new Promise((resolve) => {
144
+ let t;
145
+ const done = () => { obs.disconnect(); clearTimeout(cap); resolve(); };
146
+ const obs = new MutationObserver(() => { clearTimeout(t); t = setTimeout(done, quietMs); });
147
+ obs.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
148
+ t = setTimeout(done, quietMs);
149
+ const cap = setTimeout(done, timeout || 8000);
150
+ });
151
+ }
152
+
153
+ // Names the dashboard may show for a code, e.g. pt-BR -> "Portuguese (Brazil)" / "Brazilian Portuguese".
154
+ function displayNames(code) {
155
+ const out = new Set();
156
+ for (const languageDisplay of ['standard', 'dialect']) {
157
+ try {
158
+ const dn = new Intl.DisplayNames(['en'], { type: 'language', languageDisplay });
159
+ out.add(dn.of(code).toLowerCase());
160
+ } catch (e) { /* unknown code */ }
161
+ }
162
+ return out;
163
+ }
164
+
165
+ function optionInfo(opt) {
166
+ return { el: opt, value: opt.getAttribute('data-value'), text: clean(opt.textContent) };
167
+ }
168
+
169
+ function matchOption(locale, options) {
170
+ const code = toDashboardCode(locale).toLowerCase();
171
+ const withValue = options.filter((o) => o.value);
172
+ if (withValue.length) {
173
+ const m = withValue.filter((o) => o.value.toLowerCase() === code);
174
+ return m.length === 1 ? { opt: m[0], how: 'data-value' } : null;
175
+ }
176
+ // No codes in the markup: match on visible name, or a "(pt-BR)" style code in the text.
177
+ const names = displayNames(code);
178
+ const m = options.filter((o) => {
179
+ const t = o.text.toLowerCase();
180
+ return names.has(t) || t.includes('(' + code + ')') || t.endsWith(' ' + code) || t.endsWith(' - ' + code);
181
+ });
182
+ return m.length === 1 ? { opt: m[0], how: 'visible name' } : null;
183
+ }
184
+
185
+ function closeList() {
186
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
187
+ realClick(document.body);
188
+ }
189
+
190
+ async function listDashboardLanguages() {
191
+ const trig = findTrigger().el;
192
+ if (!findList()) realClick(trig);
193
+ const list = await waitFor(findList, 'language list to open');
194
+ const opts = $$('[role=option], li', list.el).map(optionInfo);
195
+ closeList();
196
+ await waitQuiet(100);
197
+ return opts.map((o) => ({ value: o.value, text: o.text }));
198
+ }
199
+
200
+ // Does the closed dropdown show this option? The real dashboard puts extra text in the trigger
201
+ // (Material icon names like "arrow_drop_down" are text ligatures), so test "contains", not "equals".
202
+ // Fallback: the language code as a whole word, e.g. "en" in "English - en (default)".
203
+ function triggerShows(opt) {
204
+ const t = clean(findTrigger().el.textContent);
205
+ if (opt.text && t.includes(opt.text)) return true;
206
+ if (!opt.value) return false;
207
+ const esc = opt.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
208
+ return new RegExp('(^|[^\\w-])' + esc + '($|[^\\w-])', 'i').test(t);
209
+ }
210
+
211
+ async function selectLocale(locale) {
212
+ const trig = findTrigger().el;
213
+ if (!findList()) realClick(trig);
214
+ const list = await waitFor(findList, 'language list to open');
215
+ const options = $$('[role=option], li', list.el).map(optionInfo);
216
+ const m = matchOption(locale, options);
217
+ if (!m) {
218
+ closeList();
219
+ await waitQuiet(100);
220
+ return { ok: false, reason: 'no matching language in dropdown', available: options.map((o) => o.value || o.text) };
221
+ }
222
+ const wanted = m.opt.text;
223
+ if (triggerShows(m.opt)) {
224
+ closeList();
225
+ await waitQuiet(100);
226
+ return { ok: true, how: m.how, already: true };
227
+ }
228
+ realClick(m.opt.el);
229
+ // Settle: trigger shows the new language, nothing is busy, the textarea is back, DOM is quiet.
230
+ try {
231
+ await waitFor(() => triggerShows(m.opt), 'dropdown to show ' + wanted);
232
+ } catch (e) {
233
+ let now = '?';
234
+ try { now = clean(findTrigger().el.textContent); } catch (e2) { /* trigger gone */ }
235
+ throw new Error(e.message + ' (dropdown text now: "' + now.slice(0, 80) + '")');
236
+ }
237
+ await waitFor(() => !document.querySelector('[aria-busy=true]') && findTextarea(), 'description box for ' + wanted);
238
+ await waitQuiet(200);
239
+ return { ok: true, how: m.how };
240
+ }
241
+
242
+ // The important part: React tracks the last value it saw. A plain `el.value = x`
243
+ // updates React's tracker too, so the 'input' event looks like "no change" and the
244
+ // text is lost on the next render. Calling the native prototype setter skips the tracker.
245
+ function setText(el, text, naive) {
246
+ el.focus();
247
+ if (naive) {
248
+ el.value = text;
249
+ } else {
250
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set;
251
+ setter.call(el, text);
252
+ }
253
+ el.dispatchEvent(new Event('input', { bubbles: true }));
254
+ el.dispatchEvent(new Event('change', { bubbles: true }));
255
+ el.blur();
256
+ }
257
+
258
+ function waitForUserSave(log, timeout) {
259
+ return new Promise((resolve, reject) => {
260
+ const onClick = (e) => {
261
+ const b = e.target.closest && e.target.closest('button, [role=button]');
262
+ if (b && /^save draft$/i.test(clean(b.textContent))) { cleanup(); resolve(); }
263
+ };
264
+ const cleanup = () => { document.removeEventListener('click', onClick, true); clearTimeout(t); };
265
+ document.addEventListener('click', onClick, true);
266
+ const t = setTimeout(() => { cleanup(); reject(new Error('Timed out waiting for you to click Save draft')); }, timeout || 10 * 60 * 1000);
267
+ log('Check the text, then click "Save draft". I will continue after that.');
268
+ });
269
+ }
270
+
271
+ // Code points, as the CLI counts them ([...s].length), not UTF-16 units.
272
+ const cpLen = (s) => Array.from(String(s)).length;
273
+
274
+ // First 12 hex digits of SHA-256 over the UTF-8 bytes. Same as the CLI:
275
+ // createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 12)
276
+ async function shortHash(s) {
277
+ const c = typeof crypto !== 'undefined' ? crypto : null;
278
+ if (!c || !c.subtle || typeof TextEncoder !== 'function') return null;
279
+ const buf = await c.subtle.digest('SHA-256', new TextEncoder().encode(String(s)));
280
+ return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, '0')).join('').slice(0, 12);
281
+ }
282
+
283
+ /**
284
+ * Does each embedded description still match what the CLI computed from the
285
+ * listing file (length in code points + short hash)? A mismatch means the script
286
+ * was damaged on the way (for example a clipboard that changed the encoding).
287
+ * Entries without "length"/"sha" are not checked.
288
+ */
289
+ async function checkIntegrity(listings) {
290
+ const problems = [];
291
+ for (const loc of Object.keys(listings).sort()) {
292
+ const e = listings[loc] || {};
293
+ if (e.length == null && !e.sha) continue;
294
+ const text = norm(e.description);
295
+ const length = cpLen(text);
296
+ const sha = await shortHash(text);
297
+ if (e.length != null && length !== e.length) problems.push({ locale: loc, error: 'embedded text has ' + length + ' characters, the listing file has ' + e.length });
298
+ else if (e.sha && sha && sha !== e.sha) problems.push({ locale: loc, error: 'embedded text hash ' + sha + ' differs from the listing file hash ' + e.sha });
299
+ }
300
+ return problems;
301
+ }
302
+
303
+ /** Compare page text with the expected length and hash. Returns null when it matches. */
304
+ async function compareExpected(got, e) {
305
+ if (!e || (e.length == null && !e.sha)) return null;
306
+ const length = cpLen(got);
307
+ if (e.length != null && length !== e.length) return 'page has ' + length + ' characters, expected ' + e.length;
308
+ const sha = await shortHash(got);
309
+ if (e.sha && sha && sha !== e.sha) return 'page text hash ' + sha + ', expected ' + e.sha;
310
+ return null;
311
+ }
312
+
313
+ /**
314
+ * listings: { "pt_BR": { description: "...", length: 123, sha: "0123abcd4567" }, ... }
315
+ * length (code points) and sha (12 hex digits of SHA-256) are optional. When given,
316
+ * nothing is filled unless every embedded text matches them, and the verify pass
317
+ * checks the page text against them too.
318
+ * opts:
319
+ * mode: 'fill-all' fill every language, then one Save at the end (works if the dashboard keeps unsaved text)
320
+ * 'save-each' save after each language (needed if the dashboard drops unsaved text on switch)
321
+ * save: 'none' (default) | 'wait' (wait for the user to click Save draft) | 'auto' (click Save draft; never submit)
322
+ * verify: true (default) walk all languages again and compare
323
+ * naive: true use plain `el.value =` (only to prove the mock is hostile)
324
+ * log: function
325
+ */
326
+ async function run(listings, opts) {
327
+ opts = Object.assign({ mode: 'fill-all', save: 'none', verify: true, naive: false }, opts || {});
328
+ const log = opts.log || ((...a) => console.log('[listing-fill]', ...a));
329
+ const report = { version: VERSION, mode: opts.mode, save: opts.save, integrity: null, filled: [], unmatched: [], tooLong: [], errors: [], verify: null, hint: null };
330
+
331
+ // Refuse to fill anything when the script itself was damaged.
332
+ const damaged = await checkIntegrity(listings);
333
+ report.integrity = { ok: damaged.length === 0, problems: damaged };
334
+ if (damaged.length) {
335
+ report.errors.push(...damaged);
336
+ report.hint = 'The text inside this script does not match the listing files. Nothing was filled. Rebuild the script with ext-localize and paste the file again.';
337
+ log('STOP: the script text was damaged on the way. Nothing was filled.');
338
+ log('Report:', JSON.stringify(report, null, 2));
339
+ return report;
340
+ }
341
+
342
+ const locales = Object.keys(listings).sort();
343
+ for (const loc of locales) {
344
+ const text = norm(listings[loc] && listings[loc].description);
345
+ if (!text) { report.errors.push({ locale: loc, error: 'empty description' }); continue; }
346
+ if (text.length > MAX_LEN) { report.tooLong.push({ locale: loc, length: text.length }); continue; }
347
+ try {
348
+ const sel = await selectLocale(loc);
349
+ if (!sel.ok) { report.unmatched.push({ locale: loc, dashboardCode: toDashboardCode(loc), available: sel.available }); log('No dashboard language for', loc); continue; }
350
+ const ta = findTextarea();
351
+ setText(ta.el, text, opts.naive);
352
+ await waitQuiet(150);
353
+ const now = norm(findTextarea().el.value);
354
+ const want = listings[loc].length != null ? listings[loc].length : cpLen(text);
355
+ const wrong = await compareExpected(now, listings[loc]);
356
+ report.filled.push({ locale: loc, length: cpLen(now), wantLength: want, sha: await shortHash(now), matchedBy: sel.how, textareaBy: ta.how, readBackOk: now === text && !wrong });
357
+ log('Filled', loc, '(' + cpLen(now) + ' of ' + want + ' characters)');
358
+ if (opts.mode === 'save-each') {
359
+ if (opts.save === 'auto') { realClick(findSaveDraft()); await waitQuiet(300); }
360
+ else if (opts.save === 'wait') await waitForUserSave(log, opts.waitTimeoutMs);
361
+ }
362
+ } catch (e) {
363
+ report.errors.push({ locale: loc, error: e.message });
364
+ log('Error for', loc + ':', e.message);
365
+ if (/Selectors need an update|markup may have changed/.test(e.message)) break; // stop early, do not guess
366
+ }
367
+ }
368
+
369
+ if (opts.verify && report.filled.length) {
370
+ const mismatches = [];
371
+ for (const f of report.filled) {
372
+ try {
373
+ const sel = await selectLocale(f.locale);
374
+ const got = sel.ok ? norm(findTextarea().el.value) : null;
375
+ const want = norm(listings[f.locale].description);
376
+ const wantLength = listings[f.locale].length != null ? listings[f.locale].length : cpLen(want);
377
+ const wrong = got == null ? 'language not in dropdown' : await compareExpected(got, listings[f.locale]);
378
+ if (got !== want || wrong) mismatches.push({ locale: f.locale, gotLength: got == null ? null : cpLen(got), wantLength, error: wrong || undefined });
379
+ } catch (e) {
380
+ mismatches.push({ locale: f.locale, error: e.message });
381
+ }
382
+ }
383
+ report.verify = { ok: mismatches.length === 0, mismatches };
384
+ if (mismatches.length && opts.mode === 'fill-all') {
385
+ report.hint = 'Text was lost after switching language. The dashboard probably drops unsaved text. Run again with mode "save-each".';
386
+ }
387
+ }
388
+
389
+ if (opts.mode === 'fill-all' && report.filled.length) {
390
+ if (opts.save === 'auto') { realClick(findSaveDraft()); await waitQuiet(300); log('Clicked Save draft.'); }
391
+ else log('Done. Review the languages, then click "Save draft" yourself.');
392
+ }
393
+ log('Report:', JSON.stringify(report, null, 2));
394
+ return report;
395
+ }
396
+
397
+ root.ListingFill = { VERSION, MAX_LEN, run, toDashboardCode, selectLocale, listDashboardLanguages, findTextarea, setText, checkIntegrity, shortHash };
398
+ })(typeof globalThis !== 'undefined' ? globalThis : window);
package/dist/batch.js ADDED
@@ -0,0 +1,25 @@
1
+ export function itemSize(item) {
2
+ return item.text.length + (item.description?.length ?? 0) + (item.markerHints?.join("").length ?? 0);
3
+ }
4
+ /**
5
+ * Group items into batches: at most maxItems per batch and roughly maxChars
6
+ * of text. An item bigger than maxChars gets its own batch.
7
+ */
8
+ export function makeBatches(items, limits) {
9
+ const batches = [];
10
+ let current = [];
11
+ let size = 0;
12
+ for (const item of items) {
13
+ const s = itemSize(item);
14
+ if (current.length > 0 && (current.length >= limits.maxItems || size + s > limits.maxChars)) {
15
+ batches.push(current);
16
+ current = [];
17
+ size = 0;
18
+ }
19
+ current.push(item);
20
+ size += s;
21
+ }
22
+ if (current.length)
23
+ batches.push(current);
24
+ return batches;
25
+ }