-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
70 lines (57 loc) · 1.69 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
const { join, dirname } = require('path');
const { writeFileSync, unlinkSync, existsSync, mkdirSync } = require('fs');
const GA_SCRIPT_URL = 'https://www.googletagmanager.com/gtag/js';
const ANALYTICS_FILE_NAME = 'analytics.js';
const ANALYTICS_SCRIPT_URL = `https://www.google-analytics.com/${ANALYTICS_FILE_NAME}`;
/**
* Perform a network GET request using node-fetch library
* @param {string} url
* @return {Promise<string>} string
*/
// @ts-ignore
const get = url => fetch(url).then(r => r.text());
/**
* Save a file in the file system
* @param {string} file
* @param {string} data
* @return {void}
*/
const saveFile = (file, data) => {
if (existsSync(file)) {
unlinkSync(file);
}
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, data);
};
/**
* Save the Google Analytics master file in the file system
* @param {string} folder
*/
const saveAnalyticsFile = folder => {
const file = join(folder, ANALYTICS_FILE_NAME);
return get(ANALYTICS_SCRIPT_URL)
.then(data => saveFile(file, data))
.catch(console.error);
};
/**
* Generate local version of google analytics script
* @param {Record<string, string>} options
* @return {Promise<Void>}
*/
const localga = options => {
const { id, folder, name } = options;
const file = join(folder, name);
if (!id) {
throw new Error('No google analytics ID supplied.');
}
return get(`${GA_SCRIPT_URL}?id=${id}`)
.then(async data => {
data = data.replace(ANALYTICS_SCRIPT_URL, join(folder, ANALYTICS_FILE_NAME));
saveFile(file, data);
await saveAnalyticsFile(folder);
})
.catch(console.error);
};
module.exports = localga;
module.exports.localga = localga;
module.exports.ANALYTICS_FILE_NAME = ANALYTICS_FILE_NAME;