-
Notifications
You must be signed in to change notification settings - Fork 103
/
cachebust.js
235 lines (206 loc) · 9.33 KB
/
cachebust.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
'use strict';
var fs = require('fs-extra');
var url = require('url');
var path = require('path');
var crypto = require('crypto');
var _ = require('grunt').util._;
var DEFAULT_OPTIONS = {
algorithm: 'md5',
baseDir: './',
createCopies: true,
deleteOriginals: false,
encoding: 'utf8',
jsonOutput: false,
jsonOutputFilename: 'grunt-cache-bust.json',
length: 16,
separator: '.',
queryString: false,
outputDir: '',
clearOutputDir: false,
urlPrefixes: []
};
module.exports = function(grunt) {
var isUsingQueryString = function(opts) {
return opts.queryString;
};
grunt.registerMultiTask('cacheBust', 'Bust static assets from the cache using content hashing', function() {
var opts = this.options(DEFAULT_OPTIONS);
if( opts.baseDir.substr(-1) !== '/' ) {
opts.baseDir += '/';
}
var discoveryOpts = {
cwd: path.resolve(opts.baseDir),
filter: 'isFile'
};
//clear output dir if it was set
if (opts.clearOutputDir && opts.outputDir.length > 0) {
fs.removeSync(path.resolve((discoveryOpts.cwd ? discoveryOpts.cwd + '/' +opts.outputDir : opts.outputDir)));
}
// Generate an asset map
var assetMap = grunt.file
.expand(discoveryOpts, opts.assets)
.sort()
.reverse()
.reduce(hashFile, {});
grunt.verbose.writeln('Assets found:', JSON.stringify(assetMap, null, 2));
// Write out assetMap
if (opts.jsonOutput === true) {
grunt.file.write(path.resolve(opts.baseDir, opts.jsonOutputFilename), JSON.stringify(assetMap));
}
// don't just split on the filename, if the filename = 'app.css' it will replace
// all app.css references, even to files in other dirs
// so replace this:
// "{file}"
// '{file}'
// ({file}) (css url(...))
// /{file} (css url(...))
// ={file}> (unquoted html attribute)
// ={file}\s (unquoted html attribute fonllowed by more attributes)
// "{file}\s (first entry of img srcset)
// \s{file}\s (other entries of img srcset)
// files may contain a querystring, so all with ? as closing too
var replaceEnclosedBy = [
['"', '"'],
["'", "'"],
['(', ')'],
['=', '>'],
['=', ' '],
['"', ' '],
[' ', ' ']
];
// add urlPrefixes to enclosing scenarios
if (opts.urlPrefixes && Array.isArray(opts.urlPrefixes) && opts.urlPrefixes.length > 0) {
opts.urlPrefixes.forEach(function(urlPrefix) {
replaceEnclosedBy.push([urlPrefix, '"']);
replaceEnclosedBy.push([urlPrefix, "'"]);
replaceEnclosedBy.push([urlPrefix, ")"]);
replaceEnclosedBy.push([urlPrefix, ">"]);
replaceEnclosedBy.push([urlPrefix, " "]);
});
}
// don't replace references that are already cache busted
if (!isUsingQueryString(opts)) {
replaceEnclosedBy = replaceEnclosedBy.concat(replaceEnclosedBy.map(function(reb) {
return [reb[0], '?'];
}));
}
// Go through each source file and replace them with busted file if available
var map = opts.queryString ? {} : assetMap;
var files = getFilesToBeRenamed(this.files, map, opts.baseDir);
files.forEach(replaceInFile);
grunt.log.ok(files.length + ' file' + (files.length !== 1 ? 's ' : ' ') + 'busted.');
function replaceInFile(filepath) {
var markup = grunt.file.read(filepath);
var baseDir = discoveryOpts.cwd + '/';
var relativeFileDir = path.dirname(filepath).substr(baseDir.length);
var fileDepth = 0;
if (relativeFileDir !== '') {
fileDepth = relativeFileDir.split('/').length;
}
var baseDirs = filepath.substr(baseDir.length).split('/');
_.each(assetMap, function(hashed, original) {
var replace = [
// abs path
['/' + original, '/' + hashed],
// relative
[grunt.util.repeat(fileDepth, '../') + original, grunt.util.repeat(fileDepth, '../') + hashed],
];
// find relative paths for shared dirs
var originalDirParts = path.dirname(original).split('/');
for (var i = 1; i <= fileDepth; i++) {
var fileDir = originalDirParts.slice(0, i).join('/');
var baseDir = baseDirs.slice(0, i).join('/');
if (fileDir === baseDir) {
var originalFilename = path.basename(original);
var hashedFilename = path.basename(hashed);
var dir = grunt.util.repeat(fileDepth - 1, '../') + originalDirParts.slice(i).join('/');
if (dir.substr(-1) !== '/') {
dir += '/';
}
replace.push([dir + originalFilename, dir + hashedFilename]);
}
}
_.each(replace, function(r) {
var original = r[0];
var hashed = r[1];
_.each(replaceEnclosedBy, function(reb) {
markup = markup.split(reb[0] + original + reb[1]).join(reb[0] + hashed + reb[1]);
});
});
});
grunt.file.write(filepath, markup);
}
function hashFile(obj, file) {
var absPath = path.resolve(opts.baseDir, file);
var hash = generateFileHash(grunt.file.read(absPath, {
encoding: null
}));
var newFilename = addFileHash(file, hash, opts.separator);
if (!opts.queryString) {
if (opts.createCopies) {
grunt.file.copy(absPath, path.resolve(opts.baseDir, newFilename));
}
if (opts.deleteOriginals) {
grunt.file.delete(absPath);
}
}
obj[file] = newFilename;
return obj;
}
function generateFileHash(data) {
return opts.hash || crypto.createHash(opts.algorithm).update(data, opts.encoding).digest('hex').substring(0, opts.length);
}
function addFileHash(str, hash, separator) {
if (opts.queryString) {
return str + '?' + hash;
} else {
var parsed = url.parse(str);
var pathToFile = opts.outputDir.length > 0 ? path.join(opts.outputDir, parsed.pathname.replace(/^.*[\\\/]/, '')) : parsed.pathname;
var ext = path.extname(parsed.pathname);
return (parsed.hostname ? parsed.protocol + parsed.hostname : '') + pathToFile.replace(ext, '') + separator + hash + ext;
}
}
function getFilesToBeRenamed(files, assetMap, baseDir) {
var originalConfig = files[0].orig;
// check if fully specified filenames have been busted and replace with busted file
var baseDirResolved = path.resolve(baseDir) + '/';
var cwd = process.cwd() + '/';
originalConfig.src = originalConfig.src.map(function(file) {
if( assetMap ) {
var files = [file];
if(path.resolve(cwd + file).substr(0, baseDirResolved.length) === baseDirResolved) {
files.push(path.resolve(cwd + file).substr(baseDirResolved.length));
}
var result;
files.forEach(function(file2) {
var fileResolved = path.resolve(baseDirResolved + file2);
if (!result && fileResolved.substr(0, baseDirResolved.length) === baseDirResolved && (fileResolved.substr(baseDirResolved.length)) in assetMap) {
result = assetMap[fileResolved.substr(baseDirResolved.length)];
// if original file had baseDir at the start, make sure it's there now
var baseDirNormalized = path.normalize(baseDir);
if(path.normalize(file).substr(0, baseDirNormalized.length) === baseDirNormalized) {
result = baseDir + result;
}
}
});
if(result) {
return result;
}
}
return file;
});
return grunt.file
.expand(originalConfig, originalConfig.src)
.map(function(file) {
// if the file is hashed, then the hashed file should be
// used instead of the original for replacement. This will
// only be the case if an outputDir is being used.
if (!opts.queryString && opts.outputDir && _.has(assetMap, file)) {
file = assetMap[file];
}
grunt.verbose.writeln('Busted:', file);
return path.resolve((originalConfig.cwd ? originalConfig.cwd + path.sep : '') + file);
});
}
});
};