-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
165 lines (128 loc) · 4.87 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
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
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const url = require('url');
const ignoredDirectories = require('ignore-by-default').directories();
const memoizee = require('memoizee');
const send = require('send');
const MAX_AGE = 1000 * 60 * 60 * 24 * 365; // 1 year in milliseconds
const SHORT_LEN = 7;
const LONG_LEN = 32;
const staticify = (root, options) => {
let sendOptsNonVersioned;
const setOptions = (opts = {}) => {
let defaultOptions = {
includeAll: opts.includeAll || false,
shortHash: opts.shortHash || true,
pathPrefix: opts.pathPrefix || '/',
maxAgeNonHashed: opts.maxAgeNonHashed || 0,
sendOptions: opts.sendOptions || {}
};
defaultOptions = Object.assign(defaultOptions, opts);
defaultOptions.sendOptions.root = root;
defaultOptions.sendOptions.maxAge = defaultOptions.sendOptions.maxAge || MAX_AGE;
sendOptsNonVersioned = {...defaultOptions.sendOptions};
sendOptsNonVersioned.maxAge = defaultOptions.maxAgeNonHashed;
return defaultOptions;
};
const opts = setOptions(options);
const cachedMakeHash = memoizee(filePath => {
const fileStr = fs.readFileSync(filePath, 'utf8');
let hash = crypto.createHash('md5')
.update(fileStr, 'utf8')
.digest('hex');
if (opts.shortHash) {
hash = hash.slice(0, SHORT_LEN);
}
return hash;
});
// Walks the directory tree, finding files, generating a version hash
const buildVersionHash = (directory, root = directory, vers = {}) => {
if (opts.includeAll === false && ignoredDirectories.some(d => directory.includes(d))) {
return;
}
const files = fs.readdirSync(directory);
for (const file of files) {
const absFilePath = path.posix.join(directory, file);
const stat = fs.statSync(absFilePath);
if (stat.isDirectory()) {
buildVersionHash(absFilePath, root, vers); // Whee!
} else if (stat.isFile()) {
vers[`/${path.posix.relative(root, absFilePath)}`] = {absFilePath};
}
}
return vers;
};
let versions = buildVersionHash(root);
// index.js -> index.<hash>.js
const getVersionedPath = p => {
if (!versions[p]) {
return p;
}
const fileName = path.basename(p);
const fileNameParts = fileName.split('.');
const {absFilePath} = versions[p];
fileNameParts.push(cachedMakeHash(absFilePath), fileNameParts.pop());
return path.posix.join(opts.pathPrefix, path.dirname(p), fileNameParts.join('.'));
};
// index.<hash>.js -> index.js
const stripVersion = p => {
const HASH_LEN = opts.shortHash === true ? SHORT_LEN : LONG_LEN;
const fileName = path.basename(p);
const fileNameParts = fileName.split('.');
const fileNameHashPosition = fileNameParts.length - 2;
const fileNameHash = fileNameParts[fileNameHashPosition];
const re = new RegExp(`^[0-9a-f]{${HASH_LEN}}$`, 'i');
const reResult = re.exec(fileNameHash);
if (fileNameParts.length >= 3 && fileNameHash.length === HASH_LEN &&
(reResult && reResult[0] === fileNameHash)
) {
const stripped = fileNameParts.slice(0, fileNameHashPosition);
stripped.push(fileNameParts[fileNameParts.length - 1]);
return path.join(path.dirname(p), stripped.join('.'));
}
return p;
};
const serve = req => {
// eslint-disable-next-line n/no-deprecated-api
const filePath = stripVersion(url.parse(req.url).pathname);
const sendOpts = filePath === req.url ? sendOptsNonVersioned : opts.sendOptions;
return send(req, filePath, sendOpts);
};
const middleware = (req, res, next) => {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next();
}
serve(req)
.on('error', err => {
if (err.status === 404) {
return next();
}
return next(err);
})
.pipe(res);
};
const replacePaths = fileContents => {
return Object.keys(versions).sort((a, b) => {
return b.length - a.length;
// eslint-disable-next-line unicorn/no-array-reduce
}).reduce((f, url) => {
return f.replace(new RegExp(url, 'g'), getVersionedPath(url));
}, fileContents);
};
const refresh = () => {
cachedMakeHash.clear();
versions = buildVersionHash(root);
};
return {
_versions: versions,
getVersionedPath,
stripVersion,
serve,
refresh,
middleware,
replacePaths
};
};
module.exports = staticify;