@harshankur/viewcounter 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,68 @@
1
+ const UAParser = require('ua-parser-js');
2
+
3
+ /**
4
+ * Parse user agent string to extract browser, OS, and device information
5
+ */
6
+ class UserAgentParser {
7
+ /**
8
+ * Parse user agent string
9
+ * @param {string} userAgent - User agent string from request headers
10
+ * @returns {object} Parsed user agent data
11
+ */
12
+ static parse(userAgent) {
13
+ if (!userAgent) {
14
+ return {
15
+ browser: null,
16
+ browserVersion: null,
17
+ os: null,
18
+ osVersion: null,
19
+ deviceType: null
20
+ };
21
+ }
22
+
23
+ const parser = new UAParser(userAgent);
24
+ const result = parser.getResult();
25
+
26
+ return {
27
+ browser: result.browser.name || null,
28
+ browserVersion: result.browser.version || null,
29
+ os: result.os.name || null,
30
+ osVersion: result.os.version || null,
31
+ deviceType: this.getDeviceType(result.device.type)
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Normalize device type
37
+ * @param {string} type - Device type from ua-parser-js
38
+ * @returns {string} Normalized device type
39
+ */
40
+ static getDeviceType(type) {
41
+ if (!type) return 'desktop';
42
+
43
+ const normalized = type.toLowerCase();
44
+
45
+ if (normalized === 'mobile') return 'mobile';
46
+ if (normalized === 'tablet') return 'tablet';
47
+ if (normalized === 'wearable') return 'wearable';
48
+ if (normalized === 'smarttv') return 'tv';
49
+ if (normalized === 'console') return 'console';
50
+
51
+ return 'desktop';
52
+ }
53
+
54
+ /**
55
+ * Get a simple device size category (for backward compatibility)
56
+ * @param {string} userAgent - User agent string
57
+ * @returns {string} Device size: small, medium, or large
58
+ */
59
+ static getDeviceSize(userAgent) {
60
+ const { deviceType } = this.parse(userAgent);
61
+
62
+ if (deviceType === 'mobile' || deviceType === 'wearable') return 'small';
63
+ if (deviceType === 'tablet') return 'medium';
64
+ return 'large';
65
+ }
66
+ }
67
+
68
+ module.exports = UserAgentParser;