full_url_for.js 1.0 KB

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