This repository has been archived by the owner on Dec 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
73 lines (59 loc) · 2.06 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
var replace = require('gulp-replace');
var path = require('path');
var fs = require('fs');
var checksum = require('checksum');
// Match {{cache-break:path/to/resource}}
var reCacheBreak = /{{cache-break:(.+?)}}/g;
// Match {{cdn-path:path/to/resource}}
var reCdnPath = /{{cdn-path:(.+?)}}/g;
function CacheBreaker() {
this.checksumCache = {};
}
CacheBreaker.prototype.cacheBreakPath = function(base, resource) {
base = base || process.cwd();;
var joinedPath = path.join(base, resource);
var fullPath = path.resolve(joinedPath);
var cs;
var mtime = fs.statSync(fullPath).mtime.getTime();
if (fullPath in this.checksumCache && mtime === this.checksumCache[fullPath].mtime) {
cs = this.checksumCache[fullPath].checksum;
} else {
cs = checksum(fs.readFileSync(fullPath));
this.checksumCache[fullPath] = { checksum: cs, mtime: mtime };
}
var dirname = path.dirname(resource);
var extname = path.extname(resource);
var basename = path.basename(resource, extname);
return path.join(dirname, basename + '.' + cs.substring(0, 10) + extname);
};
CacheBreaker.prototype.cdnUri = function(base, resource, host, secure) {
if (host) {
var prefix = (secure === false ? 'http://' : 'https://');
return prefix + host + this.cacheBreakPath(base, resource);
} else {
return this.cacheBreakPath(base, resource);
}
};
CacheBreaker.prototype.gulpCbPath = function(base) {
return replace(reCacheBreak, function(match, resource) {
return this.cacheBreakPath(base, resource);
}.bind(this));
};
CacheBreaker.prototype.gulpCdnUri = function(base, host, secure) {
return replace(reCdnPath, function(match, resource) {
return this.cdnUri(base, resource, host, secure);
}.bind(this));
};
CacheBreaker.prototype.symlinkCbPaths = function() {
Object.keys(this.checksumCache).forEach(function(fullPath) {
var cbPath = this.cacheBreakPath('/', fullPath);
try {
fs.symlinkSync(path.basename(fullPath), cbPath);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
}.bind(this));
};
module.exports = CacheBreaker;