url_for.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. const { parse } = require('url');
  3. const encodeURL = require('./encode_url');
  4. const relative_url = require('./relative_url');
  5. const prettyUrls = require('./pretty_urls');
  6. const Cache = require('./cache');
  7. const cache = new Cache();
  8. function urlForHelper(path = '/', options) {
  9. if (/^(#|\/\/|http(s)?:)/.test(path)) return path;
  10. const { config } = this;
  11. options = Object.assign({
  12. relative: config.relative_link
  13. }, options);
  14. // Resolve relative url
  15. if (options.relative) {
  16. return relative_url(this.path, path);
  17. }
  18. const { root } = config;
  19. const prettyUrlsOptions = Object.assign({
  20. trailing_index: true,
  21. trailing_html: true
  22. }, config.pretty_urls);
  23. // cacheId is designed to works across different hexo.config & options
  24. return cache.apply(`${config.url}-${root}-${prettyUrlsOptions.trailing_index}-${prettyUrlsOptions.trailing_html}-${path}`, () => {
  25. const sitehost = parse(config.url).hostname || config.url;
  26. const data = new URL(path, `http://${sitehost}`);
  27. // Exit if input is an external link or a data url
  28. if (data.hostname !== sitehost || data.origin === 'null') {
  29. return path;
  30. }
  31. // Prepend root path
  32. path = encodeURL((root + path).replace(/\/{2,}/g, '/'));
  33. path = prettyUrls(path, prettyUrlsOptions);
  34. return path;
  35. });
  36. }
  37. module.exports = urlForHelper;