diff --git a/lib/url_for.ts b/lib/url_for.ts index 7ab5040..35234a8 100644 --- a/lib/url_for.ts +++ b/lib/url_for.ts @@ -5,14 +5,38 @@ import prettyUrls from './pretty_urls'; import Cache from './cache'; const cache = new Cache(); -function urlForHelper(path = '/', options) { +/** + * url_for options type + * @example + * // to call this type + * type urlOpt = Parameters[1]; + */ +interface UrlForOptions { + relative?: boolean; +} + +/** + * get url relative to base URL (config_yml.url) + * @param path relative path inside `source` folder (config_yml.source_dir) + * @param options + * @returns + * @example + * // global `hexo` must be exist when used this function inside plugin + * const Hutil = require('hexo-util') + * console.log(Hutil.url_for.bind(hexo)('path/to/file/inside/source.css')); // https://example.com/path/to/file/inside/source.css + */ +function urlForHelper(path = '/', options: UrlForOptions | null = {}) { if (/^(#|\/\/|http(s)?:)/.test(path)) return path; const { config } = this; - options = Object.assign({ - relative: config.relative_link - }, options); + options = Object.assign( + { + relative: config.relative_link + }, + // fallback empty object when options filled with NULL + options || {} + ); // Resolve relative url if (options.relative) { @@ -20,28 +44,34 @@ function urlForHelper(path = '/', options) { } const { root } = config; - const prettyUrlsOptions = Object.assign({ - trailing_index: true, - trailing_html: true - }, config.pretty_urls); + const prettyUrlsOptions = Object.assign( + { + trailing_index: true, + trailing_html: true + }, + config.pretty_urls + ); // cacheId is designed to works across different hexo.config & options - return cache.apply(`${config.url}-${root}-${prettyUrlsOptions.trailing_index}-${prettyUrlsOptions.trailing_html}-${path}`, () => { - const sitehost = parse(config.url).hostname || config.url; - const data = new URL(path, `http://${sitehost}`); + return cache.apply( + `${config.url}-${root}-${prettyUrlsOptions.trailing_index}-${prettyUrlsOptions.trailing_html}-${path}`, + () => { + const sitehost = parse(config.url).hostname || config.url; + const data = new URL(path, `http://${sitehost}`); - // Exit if input is an external link or a data url - if (data.hostname !== sitehost || data.origin === 'null') { - return path; - } + // Exit if input is an external link or a data url + if (data.hostname !== sitehost || data.origin === 'null') { + return path; + } - // Prepend root path - path = encodeURL((root + path).replace(/\/{2,}/g, '/')); + // Prepend root path + path = encodeURL((root + path).replace(/\/{2,}/g, '/')); - path = prettyUrls(path, prettyUrlsOptions); + path = prettyUrls(path, prettyUrlsOptions); - return path; - }); + return path; + } + ); } export = urlForHelper;