VirtualUrlPlugin.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Natsu @xiaoxiaojx
  4. */
  5. "use strict";
  6. const NormalModule = require("../NormalModule");
  7. const { getContext } = require("../loaders/LoaderRunner");
  8. const { isAbsolute, join } = require("../util/fs");
  9. const { parseResourceWithoutFragment } = require("../util/identifier");
  10. const memoize = require("../util/memoize");
  11. const getModuleNotFoundError = memoize(() =>
  12. require("../errors/ModuleNotFoundError")
  13. );
  14. const DEFAULT_SCHEME = "virtual";
  15. const PLUGIN_NAME = "VirtualUrlPlugin";
  16. /** @import Compiler from "../Compiler" */
  17. /**
  18. * @import {
  19. * VirtualModule as VirtualModuleConfig,
  20. * VirtualModuleContent as VirtualModuleInput,
  21. * VirtualUrlOptions
  22. * } from "../../declarations/plugins/schemes/VirtualUrlPlugin"
  23. */
  24. /** @typedef {(loaderContext: LoaderContext<EXPECTED_ANY>) => Promise<string | Buffer> | string | Buffer} SourceFn */
  25. /** @typedef {() => string} VersionFn */
  26. /** @typedef {{ [key: string]: VirtualModuleInput }} VirtualModules */
  27. /**
  28. * Defines the loader context type used by this module.
  29. * @template T
  30. * @typedef {import("../../declarations/LoaderContext").LoaderContext<T>} LoaderContext
  31. */
  32. /**
  33. * Normalizes a virtual module definition into a standard format
  34. * @param {VirtualModuleInput} virtualConfig The virtual module to normalize
  35. * @returns {VirtualModuleConfig} The normalized virtual module
  36. */
  37. function normalizeModule(virtualConfig) {
  38. if (typeof virtualConfig === "string") {
  39. return {
  40. type: "",
  41. source() {
  42. return virtualConfig;
  43. }
  44. };
  45. } else if (typeof virtualConfig === "function") {
  46. return {
  47. type: "",
  48. source: virtualConfig
  49. };
  50. }
  51. return virtualConfig;
  52. }
  53. /** @typedef {{ [key: string]: VirtualModuleConfig }} NormalizedModules */
  54. /**
  55. * Normalizes all virtual modules with the given scheme
  56. * @param {VirtualModules} virtualConfigs The virtual modules to normalize
  57. * @param {string} scheme The URL scheme to use
  58. * @returns {NormalizedModules} The normalized virtual modules
  59. */
  60. function normalizeModules(virtualConfigs, scheme) {
  61. return Object.keys(virtualConfigs).reduce((pre, id) => {
  62. pre[toVid(id, scheme)] = normalizeModule(virtualConfigs[id]);
  63. return pre;
  64. }, /** @type {NormalizedModules} */ ({}));
  65. }
  66. /**
  67. * Converts a module id and scheme to a virtual module id
  68. * @param {string} id The module id
  69. * @param {string} scheme The URL scheme
  70. * @returns {string} The virtual module id
  71. */
  72. function toVid(id, scheme) {
  73. return `${scheme}:${id}`;
  74. }
  75. /**
  76. * Converts a virtual module id to a module id
  77. * @param {string} vid The virtual module id
  78. * @param {string} scheme The URL scheme
  79. * @returns {string} The module id
  80. */
  81. function fromVid(vid, scheme) {
  82. return vid.replace(`${scheme}:`, "");
  83. }
  84. const VALUE_DEP_VERSION = `webpack/${PLUGIN_NAME}/version`;
  85. /**
  86. * Converts a module id and scheme to a cache key
  87. * @param {string} id The module id
  88. * @param {string} scheme The URL scheme
  89. * @returns {string} The cache key
  90. */
  91. function toCacheKey(id, scheme) {
  92. return `${VALUE_DEP_VERSION}/${toVid(id, scheme)}`;
  93. }
  94. class VirtualUrlPlugin {
  95. /**
  96. * Creates an instance of VirtualUrlPlugin.
  97. * @param {VirtualModules} modules The virtual modules
  98. * @param {Omit<VirtualUrlOptions, "modules"> | string=} schemeOrOptions The URL scheme to use
  99. */
  100. constructor(modules, schemeOrOptions) {
  101. /** @type {VirtualUrlOptions} */
  102. this.options = {
  103. modules,
  104. ...(typeof schemeOrOptions === "string"
  105. ? { scheme: schemeOrOptions }
  106. : schemeOrOptions || {})
  107. };
  108. /** @type {string} */
  109. this.scheme = this.options.scheme || DEFAULT_SCHEME;
  110. /** @type {VirtualUrlOptions["context"]} */
  111. this.context = this.options.context || "auto";
  112. /** @type {NormalizedModules} */
  113. this.modules = normalizeModules(this.options.modules, this.scheme);
  114. }
  115. /**
  116. * Applies the plugin by registering its hooks on the compiler.
  117. * @param {Compiler} compiler the compiler instance
  118. * @returns {void}
  119. */
  120. apply(compiler) {
  121. compiler.hooks.validate.tap(PLUGIN_NAME, () => {
  122. compiler.validate(
  123. () => require("../../schemas/plugins/schemes/VirtualUrlPlugin.json"),
  124. this.options,
  125. {
  126. name: "Virtual Url Plugin",
  127. baseDataPath: "options"
  128. },
  129. (options) =>
  130. require("../../schemas/plugins/schemes/VirtualUrlPlugin.check")(
  131. options
  132. )
  133. );
  134. });
  135. const scheme = this.scheme;
  136. const cachedParseResourceWithoutFragment =
  137. parseResourceWithoutFragment.bindCache(compiler.root);
  138. compiler.hooks.compilation.tap(
  139. PLUGIN_NAME,
  140. (compilation, { normalModuleFactory }) => {
  141. compilation.hooks.assetPath.tap(
  142. { name: PLUGIN_NAME, before: "TemplatedPathPlugin" },
  143. (path, data) => {
  144. if (data.filename && this.modules[data.filename]) {
  145. /**
  146. * Returns safe path.
  147. * @param {string} str path
  148. * @returns {string} safe path
  149. */
  150. const toSafePath = (str) =>
  151. `__${str
  152. .replace(/:/g, "__")
  153. .replace(/^[^a-z0-9]+|[^a-z0-9]+$/gi, "")
  154. .replace(/[^a-z0-9._-]+/gi, "_")}`;
  155. // filename: virtual:logo.svg -> __virtual__logo.svg
  156. data.filename = toSafePath(data.filename);
  157. }
  158. return path;
  159. }
  160. );
  161. normalModuleFactory.hooks.resolveForScheme
  162. .for(scheme)
  163. .tap(PLUGIN_NAME, (resourceData) => {
  164. const virtualConfig = this.findVirtualModuleConfigById(
  165. resourceData.resource
  166. );
  167. const url = cachedParseResourceWithoutFragment(
  168. resourceData.resource
  169. );
  170. const path = url.path;
  171. const type = virtualConfig.type || "";
  172. const context = virtualConfig.context || this.context;
  173. resourceData.path = path + type;
  174. resourceData.resource = path;
  175. if (context === "auto") {
  176. const context = getContext(path);
  177. if (context === path) {
  178. resourceData.context = compiler.context;
  179. } else {
  180. const resolvedContext = fromVid(context, scheme);
  181. resourceData.context = isAbsolute(resolvedContext)
  182. ? resolvedContext
  183. : join(
  184. /** @type {import("..").InputFileSystem} */
  185. (compiler.inputFileSystem),
  186. compiler.context,
  187. resolvedContext
  188. );
  189. }
  190. } else if (context && typeof context === "string") {
  191. resourceData.context = context;
  192. } else {
  193. resourceData.context = compiler.context;
  194. }
  195. if (virtualConfig.version) {
  196. const cacheKey = toCacheKey(resourceData.resource, scheme);
  197. const cacheVersion = this.getCacheVersion(virtualConfig.version);
  198. compilation.valueCacheVersions.set(
  199. cacheKey,
  200. /** @type {string} */ (cacheVersion)
  201. );
  202. }
  203. return true;
  204. });
  205. const hooks = NormalModule.getCompilationHooks(compilation);
  206. hooks.readResource
  207. .for(scheme)
  208. .tapAsync(PLUGIN_NAME, async (loaderContext, callback) => {
  209. const { resourcePath } = loaderContext;
  210. const module = /** @type {NormalModule} */ (loaderContext._module);
  211. const cacheKey = toCacheKey(resourcePath, scheme);
  212. const addVersionValueDependency = () => {
  213. if (!module || !module.buildInfo) return;
  214. const buildInfo = module.buildInfo;
  215. if (!buildInfo.valueDependencies) {
  216. buildInfo.valueDependencies = new Map();
  217. }
  218. const cacheVersion = compilation.valueCacheVersions.get(cacheKey);
  219. if (compilation.valueCacheVersions.has(cacheKey)) {
  220. buildInfo.valueDependencies.set(
  221. cacheKey,
  222. /** @type {string} */ (cacheVersion)
  223. );
  224. }
  225. };
  226. try {
  227. const virtualConfig =
  228. this.findVirtualModuleConfigById(resourcePath);
  229. const content = await virtualConfig.source(loaderContext);
  230. addVersionValueDependency();
  231. callback(null, content);
  232. } catch (err) {
  233. callback(/** @type {Error} */ (err));
  234. }
  235. });
  236. }
  237. );
  238. }
  239. /**
  240. * Finds virtual module config by id.
  241. * @param {string} id The module id
  242. * @returns {VirtualModuleConfig} The virtual module config
  243. */
  244. findVirtualModuleConfigById(id) {
  245. const config = this.modules[id];
  246. if (!config) {
  247. throw new (getModuleNotFoundError())(
  248. null,
  249. new Error(`Can't resolve virtual module ${id}`),
  250. {
  251. name: `virtual module ${id}`
  252. }
  253. );
  254. }
  255. return config;
  256. }
  257. /**
  258. * Get the cache version for a given version value
  259. * @param {VersionFn | true | string} version The version value or function
  260. * @returns {string | undefined} The cache version
  261. */
  262. getCacheVersion(version) {
  263. return version === true
  264. ? undefined
  265. : (typeof version === "function" ? version() : version) || "unset";
  266. }
  267. }
  268. VirtualUrlPlugin.DEFAULT_SCHEME = DEFAULT_SCHEME;
  269. module.exports = VirtualUrlPlugin;