-
Notifications
You must be signed in to change notification settings - Fork 4
/
browscap.js
94 lines (79 loc) · 2.43 KB
/
browscap.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var browsers = []
, inifile = './browscap.ini'
exports.setIni = function(filename) {
inifile = filename
// Re-parse if parsed before
if (browsers.length) {
browsers = parse(filename)
}
}
function parse(filename) {
var current = {}
, browserArray = []
, patternIndex = []
require('fs')
.readFileSync(filename, 'ascii')
.split(/[\r\n]+/)
.forEach(function(line) {
// Skip comments and blank lines
if (/^\s*(;|$)/.test(line)) {
return
}
if (line[0] == '[') {
var pattern = line.slice(1, -1)
// Convert the pattern into a proper regex
current = {
__regex__: new RegExp('^'
+ pattern.replace(/\./g, '\\.')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\//g, '\\/')
.replace(/\-/g, '\\-')
.replace(/\*/g, '.*')
.replace(/\?/g, '.?')
.replace(/\+/g, '\\+')
+ '$'),
__pattern__: pattern
}
browserArray.push(current) // Push new browser object onto array
patternIndex.push(pattern) // Push pattern onto pattern index
} else {
var parts = line.split('=')
, name = parts[0]
, value = parts[1]
if (value[0] == '"' && value.slice(-1) == '"') {
value = value.slice(1, -1)
}
current[name] = value
}
})
//copy properties from parent definition, with up to depth=2 parents
for (var depth = 0; depth < 2; depth++) {
for (var i = 0; i < browserArray.length; i++) {
var current = browserArray[i]
if (current.hasOwnProperty('Parent')) {
var j = patternIndex.lastIndexOf(current['Parent'])
for (var key in browserArray[j]) {
if (key != '__regex__' && key != 'Parent' && typeof browserArray[i][key] == 'undefined') {
browserArray[i][key] = browserArray[j][key]
}
}
}
}
}
browserArray.sort(function(a, b) {
return b.__pattern__.length - a.__pattern__.length;
});
return browserArray
}
exports.getBrowser = function(userAgent) {
if (!browsers.length) {
browsers = parse(inifile)
}
// Test user agent against each browser regex
for (var i = 0; i < browsers.length; i++) {
if (browsers[i].__regex__.test(userAgent)) {
return browsers[i]
}
}
}