1 | const crypto = require('crypto');
|
2 | const fs = require('fs');
|
3 | const pkg = require('../package.json');
|
4 | const path = require('path');
|
5 | const glob = require('glob');
|
6 |
|
7 |
|
8 | function createHashFromContent(content) {
|
9 | const hash = crypto.createHash('sha256');
|
10 | hash.update(content);
|
11 | return hash.digest('hex');
|
12 | }
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function createCacheKey(source, options) {
|
18 | const content = `${source} ${JSON.stringify(options)} ${JSON.stringify(pkg)}`;
|
19 | return createHashFromContent(content);
|
20 | }
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | function retrieveFromCache(cacheKey, cacheDir) {
|
26 | if (cacheDir) {
|
27 | try {
|
28 | return fs.readFileSync(path.join(cacheDir, `${cacheKey}.js`), 'utf8');
|
29 | } catch (e) { void(0); }
|
30 | }
|
31 | return null;
|
32 | }
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | function pruneCache(usedCacheKeys, allCacheKeys, cacheDir) {
|
38 | if (cacheDir) {
|
39 | const unusedKeys = allCacheKeys.filter(key => usedCacheKeys.indexOf(key) === -1);
|
40 | unusedKeys.forEach(key => {
|
41 | fs.unlinkSync(path.join(cacheDir, `${key}.js`));
|
42 | });
|
43 | }
|
44 | }
|
45 |
|
46 | function getCacheKeysFromDisk(cacheDir) {
|
47 | if (cacheDir) {
|
48 | return glob.sync(path.join(cacheDir, '*.js')).map(fileName => path.basename(fileName, '.js'));
|
49 | }
|
50 | return [];
|
51 | }
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | function saveToCache(cacheKey, minifiedCode, cacheDir) {
|
57 | if (cacheDir) {
|
58 | fs.writeFileSync(path.join(cacheDir, `${cacheKey}.js`), minifiedCode);
|
59 | }
|
60 | }
|
61 |
|
62 | module.exports = {
|
63 | createHashFromContent,
|
64 | createCacheKey,
|
65 | retrieveFromCache,
|
66 | pruneCache,
|
67 | getCacheKeysFromDisk,
|
68 | saveToCache,
|
69 | };
|