From 536bf4e4888dc293a374c531b99175c5afd50de7 Mon Sep 17 00:00:00 2001 From: Antti Mattila <72422+pihvi@users.noreply.github.com> Date: Wed, 10 Jun 2020 13:28:48 +0300 Subject: [PATCH] Store hashed path to versions and check it matches request --- index.js | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/index.js b/index.js index fa2e85d..93e6ce0 100644 --- a/index.js +++ b/index.js @@ -66,7 +66,12 @@ const staticify = (root, options) => { if (stat.isDirectory()) { buildVersionHash(absFilePath, root, vers); // Whee! } else if (stat.isFile()) { - vers[`/${path.posix.relative(root, absFilePath)}`] = {absFilePath}; + const p = `/${path.posix.relative(root, absFilePath)}`; + const fileName = path.basename(p); + const fileNameParts = fileName.split('.'); + fileNameParts.push(cachedMakeHash(absFilePath), fileNameParts.pop()); + const versionedPath = path.posix.join(opts.pathPrefix, path.dirname(p), fileNameParts.join('.')); + vers[p] = {absFilePath, versionedPath}; } }); @@ -76,18 +81,7 @@ const staticify = (root, options) => { let versions = buildVersionHash(root); // index.js -> index..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('.')); - }; + const getVersionedPath = p => versions[p] ? versions[p].versionedPath : p; // index..js -> index.js const stripVersion = p => { @@ -115,8 +109,10 @@ const staticify = (root, options) => { const serve = req => { // eslint-disable-next-line node/no-deprecated-api - const filePath = stripVersion(url.parse(req.url).pathname); - const sendOpts = filePath === req.url ? sendOptsNonVersioned : opts.sendOptions; + const urlPath = url.parse(req.url).pathname; + const filePath = stripVersion(urlPath); + const versionMatch = filePath !== req.url && versions[filePath] && versions[filePath].versionedPath === urlPath; + const sendOpts = versionMatch ? opts.sendOptions : sendOptsNonVersioned; return send(req, filePath, sendOpts); };