-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
73 lines (68 loc) · 1.38 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
const db = require('./db/agents.lock.js');
/**
* Direct access
*/
exports.db = db;
/**
* Parse a user agent string
*/
exports.parse = (agentStr, callback) => {
const decoded = safeDecode(agentStr);
let data = null;
for (let i = 0; i < db.agents.length; i++) {
if (db.agents[i][0].test(decoded)) {
data = exports.format(db.agents[i], i);
break;
}
}
if (callback) {
callback(null, data);
}
return data;
}
/**
* Return _all_ matches for a user agent, not just the first
*/
exports.parseAll = (agentStr, callback) => {
const decoded = safeDecode(agentStr);
let datas = [];
for (let i = 0; i < db.agents.length; i++) {
if (db.agents[i][0].test(decoded)) {
datas.push(exports.format(db.agents[i], i));
}
}
if (callback) {
callback(null, datas);
}
return datas;
}
/**
* Nicely format a matcher
*/
exports.format = (match, idx) => {
if (match) {
return {
regex: match[0],
name: db.tags[match[1]] || null,
type: db.tags[match[2]] || null,
os: db.tags[match[3]] || null,
nameId: match[1] || null,
typeId: match[2] || null,
osId: match[3] || null,
bot: match[4] || false,
index: idx,
};
} else {
return null;
}
}
/**
* Decode uri components without failing
*/
function safeDecode(str) {
try {
return decodeURIComponent(str);
} catch (err) {
return str;
}
}