-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_i18n.js
More file actions
67 lines (59 loc) · 1.75 KB
/
Copy pathconvert_i18n.js
File metadata and controls
67 lines (59 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const fs = require('fs');
const path = require('path');
const messages = JSON.parse(fs.readFileSync('_locales/en/messages.json', 'utf8'));
function unflatten(flatObj) {
const result = {};
for (const key in flatObj) {
const parts = key.split('_');
let current = result;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (i === parts.length - 1) {
// Leaf
// Check if message has newlines -> was array
const msg = flatObj[key].message;
current[part] = msg.includes('\n') ? 'ARRAY_MARKER' : 'STRING_MARKER';
} else {
current[part] = current[part] || {};
current = current[part];
}
}
}
return result;
}
const structure = unflatten(messages);
function generateShim(obj, prefix = '') {
let props = [];
for (const key in obj) {
const flatKey = prefix + key;
if (obj[key] === 'ARRAY_MARKER') {
props.push(`get ${key}() { return (chrome.i18n.getMessage("${flatKey}") || "").split('\n'); }`);
} else if (obj[key] === 'STRING_MARKER') {
props.push(`get ${key}() { return chrome.i18n.getMessage("${flatKey}"); }`);
} else {
props.push(`${key}: { ${generateShim(obj[key], flatKey + '_')} }`);
}
}
return props.join(',\n');
}
const shimCode = `
/**
* Translations shim for AutoFill Plugin
* Maps old nested structure to chrome.i18n.getMessage()
*/
const t_proxy = {
${generateShim(structure)}
};
const TRANSLATIONS = {
en: t_proxy,
no: t_proxy,
get current() { return t_proxy; }
};
if (typeof window !== "undefined") {
window.TRANSLATIONS = TRANSLATIONS;
} else {
globalThis.TRANSLATIONS = TRANSLATIONS;
}
`;
fs.writeFileSync('translations.js', shimCode);
console.log('Wrote translations.js shim from messages.json');