This repository has been archived by the owner on Jul 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 497
/
index.js
100 lines (77 loc) · 2.26 KB
/
index.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
95
96
97
98
99
100
var path = require('path'),
fs = require('fs'),
yaml = require('yamlparser');
var file = path.join(__dirname, '..', 'regexes.yaml');
var regexes = fs.readFileSync(file, 'utf8');
regexes = yaml.eval(regexes);
var ua_parsers = regexes.user_agent_parsers.map(function(obj) {
var regexp = new RegExp(obj.regex),
famRep = obj.family_replacement,
majorVersionRep = obj.v1_replacement;
function parser(ua) {
var m = ua.match(regexp);
if (!m) { return null; }
var family = famRep ? famRep.replace('$1', m[1]) : m[1];
var obj = new UserAgent(family);
obj.major = parseInt(majorVersionRep ? majorVersionRep : m[2]);
obj.minor = m[3] ? parseInt(m[3]) : null;
obj.patch = m[4] ? parseInt(m[4]) : null;
return obj;
}
return parser;
});
var os_parsers = regexes.os_parsers.map(function(obj) {
var regexp = new RegExp(obj.regex),
osRep = obj.os_replacement;
function parser(ua) {
var m = ua.match(regexp);
if(!m) { return null; }
var os = (osRep ? osRep : m[1]) + (m.length > 2 ? " " + m[2] : "") + (m.length > 3 ? "." + m[3] : "");
return os;
}
return parser;
});
exports.parse = parse;
function parse(ua) {
var os, i;
for (i=0; i < ua_parsers.length; i++) {
var result = ua_parsers[i](ua);
if (result) { break; }
}
for (i=0; i < os_parsers.length; i++) {
os = os_parsers[i](ua);
if (os) { break; }
}
if(!result) { result = new UserAgent(); }
result.os = os;
return result;
}
function UserAgent(family) {
this.family = family || 'Other';
}
UserAgent.prototype.toVersionString = function() {
var output = '';
if (this.major != null) {
output += this.major;
if (this.minor != null) {
output += '.' + this.minor;
if (this.patch != null) {
output += '.' + this.patch;
}
}
}
return output;
};
UserAgent.prototype.toString = function() {
var suffix = this.toVersionString();
if (suffix) { suffix = ' ' + suffix; }
return this.family + suffix;
};
UserAgent.prototype.toFullString = function() {
return this.toString() + (this.os ? "/" + this.os : "");
};
if (require.main === module) {
var output, input = process.argv[2];
if (!input) { process.exit(1); }
process.stdout.write(parse(input).toString());
}