webpack/lib/util/identifier.js

402 lines
12 KiB
JavaScript
Raw Normal View History

2018-07-30 23:08:51 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
2018-07-30 23:08:51 +08:00
const path = require("path");
const WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/;
2020-03-13 00:51:26 +08:00
const SEGMENTS_SPLIT_REGEXP = /([|!])/;
const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g;
2023-05-01 04:51:59 +08:00
/**
* @param {string} relativePath relative path
* @returns {string} request
*/
const relativePathToRequest = (relativePath) => {
if (relativePath === "") return "./.";
if (relativePath === "..") return "../.";
if (relativePath.startsWith("../")) return relativePath;
return `./${relativePath}`;
};
/**
* @param {string} context context for relative path
* @param {string} maybeAbsolutePath path to make relative
* @returns {string} relative path in request style
*/
const absoluteToRequest = (context, maybeAbsolutePath) => {
2018-12-23 20:22:07 +08:00
if (maybeAbsolutePath[0] === "/") {
if (
maybeAbsolutePath.length > 1 &&
maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/"
) {
// this 'path' is actually a regexp generated by dynamic requires.
// Don't treat it as an absolute path.
return maybeAbsolutePath;
}
const querySplitPos = maybeAbsolutePath.indexOf("?");
let resource =
querySplitPos === -1
? maybeAbsolutePath
: maybeAbsolutePath.slice(0, querySplitPos);
resource = relativePathToRequest(path.posix.relative(context, resource));
return querySplitPos === -1
? resource
: resource + maybeAbsolutePath.slice(querySplitPos);
}
2018-12-23 20:22:07 +08:00
if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) {
const querySplitPos = maybeAbsolutePath.indexOf("?");
let resource =
querySplitPos === -1
? maybeAbsolutePath
: maybeAbsolutePath.slice(0, querySplitPos);
resource = path.win32.relative(context, resource);
if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) {
resource = relativePathToRequest(
resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/")
);
}
return querySplitPos === -1
? resource
: resource + maybeAbsolutePath.slice(querySplitPos);
}
2018-12-23 20:22:07 +08:00
// not an absolute path
return maybeAbsolutePath;
};
/**
* @param {string} context context for relative path
* @param {string} relativePath path
* @returns {string} absolute path
*/
const requestToAbsolute = (context, relativePath) => {
if (relativePath.startsWith("./") || relativePath.startsWith("../")) {
return path.join(context, relativePath);
}
return relativePath;
};
/** @typedef {EXPECTED_OBJECT} AssociatedObjectForCache */
2024-08-06 11:08:48 +08:00
/**
* @template T
* @typedef {(value: string, cache?: AssociatedObjectForCache) => T} MakeCacheableResult
2024-08-06 11:08:48 +08:00
*/
/**
* @template T
* @typedef {(value: string) => T} BindCacheResultFn
2024-08-06 11:08:48 +08:00
*/
/**
* @template T
* @typedef {(cache: AssociatedObjectForCache) => BindCacheResultFn<T>} BindCache
2024-08-06 11:08:48 +08:00
*/
/**
* @template T
* @param {((value: string) => T)} realFn real function
2024-08-06 11:08:48 +08:00
* @returns {MakeCacheableResult<T> & { bindCache: BindCache<T> }} cacheable function
*/
const makeCacheable = (realFn) => {
2024-08-06 11:08:48 +08:00
/**
* @template T
* @typedef {Map<string, T>} CacheItem
*/
/** @type {WeakMap<AssociatedObjectForCache, CacheItem<T>>} */
const cache = new WeakMap();
2024-08-06 11:08:48 +08:00
/**
* @param {AssociatedObjectForCache} associatedObjectForCache an object to which the cache will be attached
2024-08-06 11:08:48 +08:00
* @returns {CacheItem<T>} cache item
*/
const getCache = (associatedObjectForCache) => {
const entry = cache.get(associatedObjectForCache);
if (entry !== undefined) return entry;
2024-08-06 11:08:48 +08:00
/** @type {Map<string, T>} */
const map = new Map();
cache.set(associatedObjectForCache, map);
return map;
};
2024-08-06 11:08:48 +08:00
/** @type {MakeCacheableResult<T> & { bindCache: BindCache<T> }} */
const fn = (str, associatedObjectForCache) => {
if (!associatedObjectForCache) return realFn(str);
const cache = getCache(associatedObjectForCache);
const entry = cache.get(str);
if (entry !== undefined) return entry;
const result = realFn(str);
cache.set(str, result);
return result;
};
2024-08-06 11:08:48 +08:00
/** @type {BindCache<T>} */
fn.bindCache = (associatedObjectForCache) => {
const cache = getCache(associatedObjectForCache);
2024-08-06 11:08:48 +08:00
/**
* @param {string} str string
* @returns {T} value
*/
return (str) => {
const entry = cache.get(str);
if (entry !== undefined) return entry;
const result = realFn(str);
cache.set(str, result);
return result;
};
};
return fn;
};
/** @typedef {(context: string, value: string, associatedObjectForCache?: AssociatedObjectForCache) => string} MakeCacheableWithContextResult */
/** @typedef {(context: string, value: string) => string} BindCacheForContextResultFn */
/** @typedef {(value: string) => string} BindContextCacheForContextResultFn */
/** @typedef {(associatedObjectForCache?: AssociatedObjectForCache) => BindCacheForContextResultFn} BindCacheForContext */
/** @typedef {(value: string, associatedObjectForCache?: AssociatedObjectForCache) => BindContextCacheForContextResultFn} BindContextCacheForContext */
2024-08-06 11:08:48 +08:00
/**
* @param {(context: string, identifier: string) => string} fn function
2024-08-06 11:08:48 +08:00
* @returns {MakeCacheableWithContextResult & { bindCache: BindCacheForContext, bindContextCache: BindContextCacheForContext }} cacheable function with context
*/
const makeCacheableWithContext = (fn) => {
/** @type {WeakMap<AssociatedObjectForCache, Map<string, Map<string, string>>>} */
const cache = new WeakMap();
2024-08-06 11:08:48 +08:00
/** @type {MakeCacheableWithContextResult & { bindCache: BindCacheForContext, bindContextCache: BindContextCacheForContext }} */
const cachedFn = (context, identifier, associatedObjectForCache) => {
if (!associatedObjectForCache) return fn(context, identifier);
let innerCache = cache.get(associatedObjectForCache);
if (innerCache === undefined) {
innerCache = new Map();
cache.set(associatedObjectForCache, innerCache);
}
let cachedResult;
let innerSubCache = innerCache.get(context);
if (innerSubCache === undefined) {
innerCache.set(context, (innerSubCache = new Map()));
} else {
cachedResult = innerSubCache.get(identifier);
}
if (cachedResult !== undefined) {
return cachedResult;
}
2024-07-31 04:21:27 +08:00
const result = fn(context, identifier);
innerSubCache.set(identifier, result);
return result;
};
2024-08-06 11:08:48 +08:00
/** @type {BindCacheForContext} */
cachedFn.bindCache = (associatedObjectForCache) => {
2020-01-15 06:14:47 +08:00
let innerCache;
if (associatedObjectForCache) {
innerCache = cache.get(associatedObjectForCache);
if (innerCache === undefined) {
innerCache = new Map();
cache.set(associatedObjectForCache, innerCache);
}
} else {
innerCache = new Map();
}
/**
* @param {string} context context used to create relative path
* @param {string} identifier identifier used to create relative path
* @returns {string} the returned relative path
*/
const boundFn = (context, identifier) => {
let cachedResult;
let innerSubCache = innerCache.get(context);
if (innerSubCache === undefined) {
innerCache.set(context, (innerSubCache = new Map()));
} else {
cachedResult = innerSubCache.get(identifier);
}
if (cachedResult !== undefined) {
return cachedResult;
}
2024-07-31 04:21:27 +08:00
const result = fn(context, identifier);
innerSubCache.set(identifier, result);
return result;
2020-01-15 06:14:47 +08:00
};
return boundFn;
};
2024-08-06 11:08:48 +08:00
/** @type {BindContextCacheForContext} */
2020-01-15 06:14:47 +08:00
cachedFn.bindContextCache = (context, associatedObjectForCache) => {
let innerSubCache;
if (associatedObjectForCache) {
let innerCache = cache.get(associatedObjectForCache);
if (innerCache === undefined) {
innerCache = new Map();
cache.set(associatedObjectForCache, innerCache);
}
innerSubCache = innerCache.get(context);
if (innerSubCache === undefined) {
innerCache.set(context, (innerSubCache = new Map()));
}
} else {
innerSubCache = new Map();
}
/**
* @param {string} identifier identifier used to create relative path
* @returns {string} the returned relative path
*/
const boundFn = (identifier) => {
2020-01-15 06:14:47 +08:00
const cachedResult = innerSubCache.get(identifier);
if (cachedResult !== undefined) {
return cachedResult;
}
2024-07-31 04:21:27 +08:00
const result = fn(context, identifier);
innerSubCache.set(identifier, result);
return result;
2020-01-15 06:14:47 +08:00
};
return boundFn;
};
return cachedFn;
};
/**
* @param {string} context context for relative path
* @param {string} identifier identifier for path
* @returns {string} a converted relative path
*/
2024-07-31 11:31:11 +08:00
const _makePathsRelative = (context, identifier) =>
identifier
2020-03-13 00:51:26 +08:00
.split(SEGMENTS_SPLIT_REGEXP)
.map((str) => absoluteToRequest(context, str))
.join("");
/**
* @param {string} context context for relative path
* @param {string} identifier identifier for path
* @returns {string} a converted relative path
*/
2024-07-31 11:31:11 +08:00
const _makePathsAbsolute = (context, identifier) =>
identifier
.split(SEGMENTS_SPLIT_REGEXP)
.map((str) => requestToAbsolute(context, str))
.join("");
/**
* @param {string} context absolute context path
* @param {string} request any request string may containing absolute paths, query string, etc.
* @returns {string} a new request string avoiding absolute paths when possible
*/
2024-07-31 11:31:11 +08:00
const _contextify = (context, request) =>
request
.split("!")
.map((r) => absoluteToRequest(context, r))
.join("!");
const contextify = makeCacheableWithContext(_contextify);
/**
* @param {string} context absolute context path
* @param {string} request any request string
* @returns {string} a new request string using absolute paths when possible
*/
2024-07-31 11:31:11 +08:00
const _absolutify = (context, request) =>
request
.split("!")
.map((r) => requestToAbsolute(context, r))
.join("!");
const absolutify = makeCacheableWithContext(_absolutify);
2021-05-11 15:31:46 +08:00
const PATH_QUERY_FRAGMENT_REGEXP =
/^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/;
2022-02-04 23:12:20 +08:00
const PATH_QUERY_REGEXP = /^((?:\0.|[^?\0])*)(\?.*)?$/;
2020-07-03 20:45:49 +08:00
/** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */
/** @typedef {{ resource: string, path: string, query: string }} ParsedResourceWithoutFragment */
2020-07-03 20:45:49 +08:00
/**
* @param {string} str the path with query and fragment
* @returns {ParsedResource} parsed parts
2020-07-03 20:45:49 +08:00
*/
const _parseResource = (str) => {
2024-08-06 11:08:48 +08:00
const match =
/** @type {[string, string, string | undefined, string | undefined]} */
(/** @type {unknown} */ (PATH_QUERY_FRAGMENT_REGEXP.exec(str)));
2020-07-03 20:45:49 +08:00
return {
resource: str,
path: match[1].replace(/\0(.)/g, "$1"),
query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "",
2020-07-03 20:45:49 +08:00
fragment: match[3] || ""
};
};
/**
* Parse resource, skips fragment part
* @param {string} str the path with query and fragment
* @returns {ParsedResourceWithoutFragment} parsed parts
*/
const _parseResourceWithoutFragment = (str) => {
2024-08-06 11:08:48 +08:00
const match =
/** @type {[string, string, string | undefined]} */
(/** @type {unknown} */ (PATH_QUERY_REGEXP.exec(str)));
return {
resource: str,
path: match[1].replace(/\0(.)/g, "$1"),
query: match[2] ? match[2].replace(/\0(.)/g, "$1") : ""
};
};
/**
* @param {string} filename the filename which should be undone
* @param {string} outputPath the output path that is restored (only relevant when filename contains "..")
* @param {boolean} enforceRelative true returns ./ for empty paths
* @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir
*/
2025-07-03 17:06:45 +08:00
const getUndoPath = (filename, outputPath, enforceRelative) => {
let depth = -1;
let append = "";
outputPath = outputPath.replace(/[\\/]$/, "");
for (const part of filename.split(/[/\\]+/)) {
if (part === "..") {
if (depth > -1) {
depth--;
} else {
const i = outputPath.lastIndexOf("/");
const j = outputPath.lastIndexOf("\\");
const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j);
2024-07-31 10:39:30 +08:00
if (pos < 0) return `${outputPath}/`;
append = `${outputPath.slice(pos + 1)}/${append}`;
outputPath = outputPath.slice(0, pos);
}
} else if (part !== ".") {
depth++;
}
}
return depth > 0
? `${"../".repeat(depth)}${append}`
: enforceRelative
2024-07-31 05:43:19 +08:00
? `./${append}`
: append;
};
2025-07-03 17:06:45 +08:00
module.exports.absolutify = absolutify;
module.exports.contextify = contextify;
module.exports.getUndoPath = getUndoPath;
module.exports.makePathsAbsolute = makeCacheableWithContext(_makePathsAbsolute);
module.exports.makePathsRelative = makeCacheableWithContext(_makePathsRelative);
module.exports.parseResource = makeCacheable(_parseResource);
module.exports.parseResourceWithoutFragment = makeCacheable(
_parseResourceWithoutFragment
);