Skip to content

Improve getFilenameFromUrl to work with proxy requests #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Sep 16, 2016
39 changes: 27 additions & 12 deletions lib/GetFilenameFromUrl.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
var pathJoin = require("./PathJoin");
var urlParse = require("url").parse;

function getFilenameFromUrl(publicPath, outputPath, url) {
// publicPrefix is the folder our bundle should be in
var localPrefix = publicPath || "/";
if(url.indexOf(localPrefix) !== 0) {
if(/^(https?:)?\/\//.test(localPrefix)) {
localPrefix = "/" + localPrefix.replace(/^(https?:)?\/\/[^\/]+\//, "");
// fast exit if another directory requested
if(url.indexOf(localPrefix) !== 0) return false;
} else return false;
var filename;

// localPrefix is the folder our bundle should be in
var localPrefix = urlParse(publicPath || "/");
var urlObject = urlParse(url);

// publicPath has the hostname that is not the same as request url's, should fail
if(localPrefix.hostname !== null && urlObject.hostname !== null &&
localPrefix.hostname !== urlObject.hostname) {
return false;
}

// publicPath is not in url, so it should fail
if(publicPath && localPrefix.hostname === urlObject.hostname && url.indexOf(publicPath) !== 0) {
return false;
}
// get filename from request
var filename = url.substr(localPrefix.length);
if(filename.indexOf("?") >= 0) {
filename = filename.substr(0, filename.indexOf("?"));

// strip localPrefix from the start of url
if(urlObject.pathname.indexOf(localPrefix.pathname) === 0) {
filename = urlObject.pathname.substr(localPrefix.pathname.length);
}

if(!urlObject.hostname && localPrefix.hostname &&
url.indexOf(localPrefix.path) !== 0) {
return false;
}
// and if not match, use outputPath as filename
return filename ? pathJoin(outputPath, filename) : outputPath;

}

module.exports = getFilenameFromUrl;
10 changes: 10 additions & 0 deletions test/GetFilenameFromUrl.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ describe("GetFilenameFromUrl", function() {
outputPath: "/a",
publicPath: "/",
expected: "/a/more/complex/path.js",
}, {
url: "/more/complex/path.js",
outputPath: "/a",
publicPath: "/complex",
expected: false,
}, {
url: "c.js",
outputPath: "/dist",
Expand All @@ -64,6 +69,11 @@ describe("GetFilenameFromUrl", function() {
outputPath: "/",
publicPath: "http://localhost/foo/",
expected: false,
}, {
url: "http://test.domain/test/sample.js",
outputPath: "/",
publicPath: "/test/",
expected: "/sample.js"
}
];
results.forEach(testUrl);
Expand Down