forked from duckduckgo/privacy-configuration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.js
71 lines (65 loc) · 2.38 KB
/
util.js
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
68
69
70
71
function getAllowlistedRule (rules, rulePath) {
return rules.find(function (x) { return x.rule === rulePath })
}
function addDomainRule (allowlist, domain, rule) {
const found = allowlist[domain]
const existing = found || { rules: [] }
if (!found) {
allowlist[domain] = existing
}
const newRules = rule.rules || []
newRules.forEach(function (r) { addPathRule(existing.rules, r) })
// very basic substring checking to order more-specific rules earlier (doesn't deal with regexp rules)
existing.rules.sort(function (a, b) {
return a.rule.includes(b.rule) ? -1 : b.rule.includes(a.rule) ? 1 : 0
})
}
function addPathRule (rules, rule) {
const found = getAllowlistedRule(rules, rule.rule)
const existing = found || { rule: rule.rule, domains: [], reason: '' }
if (!found) {
rules.push(existing)
}
existing.domains = Array.from(new Set(existing.domains.concat(rule.domains).sort()))
existing.reason = [existing.reason, rule.reason].filter(function (x) { return x !== '' }).join('; ')
}
function mergeAllowlistedTrackers (t1, t2) {
const res = {}
for (const dom in t1) {
addDomainRule(res, dom, t1[dom])
}
for (const dom in t2) {
addDomainRule(res, dom, t2[dom])
}
// Sort the resulting generated object by domain keys.
// This makes working with the generated config easier and more human-navigable.
return Object.keys(res).sort().reduce(function (acc, k) { acc[k] = res[k]; return acc }, {})
}
/**
* Traverse the input (JSON data) and ensure any "reason" fields are strings in the output.
*
* This allows specifying reasons as an array of strings, and converts these to
* strings in the resulting data.
*/
function inlineReasonArrays (data) {
if (Array.isArray(data)) {
return data.map(inlineReasonArrays)
} else if (typeof data === 'object' && data !== null) {
const res = {}
for (const [k, v] of Object.entries(data)) {
if (k === 'reason') {
// we collapse list 'reason' field values into a single string
res[k] = Array.isArray(v) ? v.join(' ') : v
} else {
res[k] = inlineReasonArrays(v)
}
}
return res
} else {
return data
}
}
module.exports = {
inlineReasonArrays: inlineReasonArrays,
mergeAllowlistedTrackers: mergeAllowlistedTrackers
}