getFilenameFromUrl.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = getFilenameFromUrl;
  6. var _path = _interopRequireDefault(require("path"));
  7. var _url = require("url");
  8. var _querystring = _interopRequireDefault(require("querystring"));
  9. var _mem = _interopRequireDefault(require("mem"));
  10. var _getPaths = _interopRequireDefault(require("./getPaths"));
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. const memoizedParse = (0, _mem.default)(_url.parse);
  13. function getFilenameFromUrl(context, url) {
  14. const {
  15. options
  16. } = context;
  17. const paths = (0, _getPaths.default)(context);
  18. let foundFilename;
  19. let urlObject;
  20. try {
  21. // The `url` property of the `request` is contains only `pathname`, `search` and `hash`
  22. urlObject = memoizedParse(url, false, true);
  23. } catch (_ignoreError) {
  24. return;
  25. }
  26. for (const {
  27. publicPath,
  28. outputPath
  29. } of paths) {
  30. let filename;
  31. let publicPathObject;
  32. try {
  33. publicPathObject = memoizedParse(publicPath !== "auto" && publicPath ? publicPath : "/", false, true);
  34. } catch (_ignoreError) {
  35. // eslint-disable-next-line no-continue
  36. continue;
  37. }
  38. if (urlObject.pathname && urlObject.pathname.startsWith(publicPathObject.pathname)) {
  39. filename = outputPath; // Strip the `pathname` property from the `publicPath` option from the start of requested url
  40. // `/complex/foo.js` => `foo.js`
  41. const pathname = urlObject.pathname.substr(publicPathObject.pathname.length);
  42. if (pathname) {
  43. filename = _path.default.join(outputPath, _querystring.default.unescape(pathname));
  44. }
  45. let fsStats;
  46. try {
  47. fsStats = context.outputFileSystem.statSync(filename);
  48. } catch (_ignoreError) {
  49. // eslint-disable-next-line no-continue
  50. continue;
  51. }
  52. if (fsStats.isFile()) {
  53. foundFilename = filename;
  54. break;
  55. } else if (fsStats.isDirectory() && (typeof options.index === "undefined" || options.index)) {
  56. const indexValue = typeof options.index === "undefined" || typeof options.index === "boolean" ? "index.html" : options.index;
  57. filename = _path.default.join(filename, indexValue);
  58. try {
  59. fsStats = context.outputFileSystem.statSync(filename);
  60. } catch (__ignoreError) {
  61. // eslint-disable-next-line no-continue
  62. continue;
  63. }
  64. if (fsStats.isFile()) {
  65. foundFilename = filename;
  66. break;
  67. }
  68. }
  69. }
  70. } // eslint-disable-next-line consistent-return
  71. return foundFilename;
  72. }