blob: bfcb92c74da7c4e6730be71d4509f38cd20f89a2 [file] [log] [blame]
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +02001import optionsPrototype from './optionsPrototype.json5';
2import specialOptions from './specialOptions.json5';
3
4export {optionsPrototype, specialOptions};
5
6// Adds missing options with their default value. If |dryRun| is set to false,
7// they are also saved to the sync storage area.
8export function cleanUpOptions(options, dryRun = false) {
Adrià Vilanova Martínez413cb442021-09-06 00:30:45 +02009 console.debug('[cleanUpOptions] Previous options', JSON.stringify(options));
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +020010
11 if (typeof options !== 'object' || options === null) options = {};
12
13 var ok = true;
14 for (const [opt, optMeta] of Object.entries(optionsPrototype)) {
15 if (!(opt in options)) {
16 ok = false;
17 options[opt] = optMeta['defaultValue'];
18 }
19 }
20
Adrià Vilanova Martínez413cb442021-09-06 00:30:45 +020021 console.debug('[cleanUpOptions] New options', JSON.stringify(options));
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +020022
23 if (!ok && !dryRun) {
24 chrome.storage.sync.set(options);
25 }
26
27 return options;
28}
Adrià Vilanova Martínezd269c622021-09-04 18:35:55 +020029
30// Returns a promise which returns the values of options |options| which are
31// stored in the sync storage area.
32export function getOptions(options) {
33 // Once we only target MV3, this can be greatly simplified.
Adrià Vilanova Martínez413cb442021-09-06 00:30:45 +020034 return new Promise((resolve, reject) => {
35 if (typeof options === 'string')
36 options = [options, '_forceDisabledFeatures'];
37 else if (typeof options === 'array')
38 options = [...options, '_forceDisabledFeatures'];
39 else if (options !== null)
40 console.error('Unexpected |options| parameter (expected: string, array, or null).');
Adrià Vilanova Martínezd269c622021-09-04 18:35:55 +020041
Adrià Vilanova Martínez413cb442021-09-06 00:30:45 +020042 chrome.storage.sync.get(options, items => {
43 if (chrome.runtime.lastError) return reject(chrome.runtime.lastError);
44
45 // Handle applicable kill switches which force disable features
46 if (items?._forceDisabledFeatures) {
47 for (let feature of items?._forceDisabledFeatures) {
48 items[feature] = false;
49 }
50
51 delete items._forceDisabledFeatures;
52 }
53
54 resolve(items);
55 });
56 });
Adrià Vilanova Martínezd269c622021-09-04 18:35:55 +020057}
58
59// Returns a promise which returns whether the |option| option/feature is
60// currently enabled.
61export function isOptionEnabled(option) {
62 return getOptions(option).then(options => {
63 return options?.[option] === true;
64 });
65}