forked from EFForg/https-everywhere
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexplode-regexp.js
More file actions
86 lines (74 loc) · 2.13 KB
/
Copy pathexplode-regexp.js
File metadata and controls
86 lines (74 loc) · 2.13 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* eslint-env es6, node */
const { parse } = require('regulex');
class UnsupportedRegExp extends Error {}
function explodeRegExp(re, callback) {
(function buildUrls(str, items) {
if (items.length === 0) {
callback(str + '*');
return;
}
let [first, ...rest] = items;
if (first.repeat) {
let { repeat, ...firstSub } = first;
if (repeat.max !== 1) throw new UnsupportedRegExp(first.raw);
if (repeat.min === 0) {
buildUrls(str, rest);
}
return buildUrls(str, [ firstSub, ...rest ]);
}
switch (first.type) {
case 'group': {
return buildUrls(str, first.sub.concat(rest));
}
case 'assert': {
if (first.assertionType === 'AssertBegin') {
if (str !== '*') return; // can't match begin not at the beginning
return buildUrls('', rest);
}
if (first.assertionType === 'AssertEnd') {
callback(str);
return;
}
if (first.assertionType === 'AssertLookahead' && rest.length === 0) {
return buildUrls(str, first.sub.concat(rest));
}
break;
}
case 'choice': {
for (let branch of first.branches) {
buildUrls(str, branch.concat(rest));
}
return;
}
case 'exact': {
return buildUrls(str + first.chars, rest);
}
case 'charset': {
if (first.ranges.length === 1) {
let range = first.ranges[0];
let from = range.charCodeAt(0);
let to = range.charCodeAt(1);
if (to - from < 10) {
// small range, probably won't explode
for (; from <= to; from++) {
buildUrls(str + String.fromCharCode(from), rest);
}
first.ranges.length = 0;
}
}
if (!first.classes.length && !first.exclude && !first.ranges.length) {
for (let c of first.chars) {
buildUrls(str + c, rest);
}
return;
}
break;
}
}
throw new UnsupportedRegExp(first.raw);
})('*', parse(re).tree);
};
module.exports = {
UnsupportedRegExp,
explodeRegExp
};