ResolverCachePlugin.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const LazySet = require("../util/LazySet");
  7. const makeSerializable = require("../util/makeSerializable");
  8. /** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */
  9. /** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */
  10. /** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
  11. /** @typedef {import("enhanced-resolve").Resolver} Resolver */
  12. /** @typedef {import("../CacheFacade").ItemCacheFacade} ItemCacheFacade */
  13. /** @typedef {import("../Compiler")} Compiler */
  14. /** @typedef {import("../FileSystemInfo")} FileSystemInfo */
  15. /** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */
  16. /** @typedef {import("../FileSystemInfo").SnapshotOptions} SnapshotOptions */
  17. /** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */
  18. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  19. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  20. /**
  21. * @template T
  22. * @typedef {import("tapable").SyncHook<T>} SyncHook
  23. */
  24. /**
  25. * @template H
  26. * @typedef {import("tapable").HookMapInterceptor<H>} HookMapInterceptor
  27. */
  28. class CacheEntry {
  29. /**
  30. * @param {ResolveRequest} result result
  31. * @param {Snapshot} snapshot snapshot
  32. */
  33. constructor(result, snapshot) {
  34. this.result = result;
  35. this.snapshot = snapshot;
  36. }
  37. /**
  38. * @param {ObjectSerializerContext} context context
  39. */
  40. serialize({ write }) {
  41. write(this.result);
  42. write(this.snapshot);
  43. }
  44. /**
  45. * @param {ObjectDeserializerContext} context context
  46. */
  47. deserialize({ read }) {
  48. this.result = read();
  49. this.snapshot = read();
  50. }
  51. }
  52. makeSerializable(CacheEntry, "webpack/lib/cache/ResolverCachePlugin");
  53. /**
  54. * @template T
  55. * @param {Set<T> | LazySet<T>} set set to add items to
  56. * @param {Set<T> | LazySet<T> | Iterable<T>} otherSet set to add items from
  57. * @returns {void}
  58. */
  59. const addAllToSet = (set, otherSet) => {
  60. if (set instanceof LazySet) {
  61. set.addAll(otherSet);
  62. } else {
  63. for (const item of otherSet) {
  64. set.add(item);
  65. }
  66. }
  67. };
  68. /**
  69. * @template {object} T
  70. * @param {T} object an object
  71. * @param {boolean} excludeContext if true, context is not included in string
  72. * @returns {string} stringified version
  73. */
  74. const objectToString = (object, excludeContext) => {
  75. let str = "";
  76. for (const key in object) {
  77. if (excludeContext && key === "context") continue;
  78. const value = object[key];
  79. str +=
  80. typeof value === "object" && value !== null
  81. ? `|${key}=[${objectToString(value, false)}|]`
  82. : `|${key}=|${value}`;
  83. }
  84. return str;
  85. };
  86. class ResolverCachePlugin {
  87. /**
  88. * Apply the plugin
  89. * @param {Compiler} compiler the compiler instance
  90. * @returns {void}
  91. */
  92. apply(compiler) {
  93. const cache = compiler.getCache("ResolverCachePlugin");
  94. /** @type {FileSystemInfo} */
  95. let fileSystemInfo;
  96. /** @type {SnapshotOptions | undefined} */
  97. let snapshotOptions;
  98. let realResolves = 0;
  99. let cachedResolves = 0;
  100. let cacheInvalidResolves = 0;
  101. let concurrentResolves = 0;
  102. compiler.hooks.thisCompilation.tap("ResolverCachePlugin", compilation => {
  103. snapshotOptions = compilation.options.snapshot.resolve;
  104. fileSystemInfo = compilation.fileSystemInfo;
  105. compilation.hooks.finishModules.tap("ResolverCachePlugin", () => {
  106. if (realResolves + cachedResolves > 0) {
  107. const logger = compilation.getLogger("webpack.ResolverCachePlugin");
  108. logger.log(
  109. `${Math.round(
  110. (100 * realResolves) / (realResolves + cachedResolves)
  111. )}% really resolved (${realResolves} real resolves with ${cacheInvalidResolves} cached but invalid, ${cachedResolves} cached valid, ${concurrentResolves} concurrent)`
  112. );
  113. realResolves = 0;
  114. cachedResolves = 0;
  115. cacheInvalidResolves = 0;
  116. concurrentResolves = 0;
  117. }
  118. });
  119. });
  120. /** @typedef {(err?: Error | null, resolveRequest?: ResolveRequest | null) => void} Callback */
  121. /** @typedef {ResolveRequest & { _ResolverCachePluginCacheMiss: true }} ResolveRequestWithCacheMiss */
  122. /**
  123. * @param {ItemCacheFacade} itemCache cache
  124. * @param {Resolver} resolver the resolver
  125. * @param {ResolveContext} resolveContext context for resolving meta info
  126. * @param {ResolveRequest} request the request info object
  127. * @param {Callback} callback callback function
  128. * @returns {void}
  129. */
  130. const doRealResolve = (
  131. itemCache,
  132. resolver,
  133. resolveContext,
  134. request,
  135. callback
  136. ) => {
  137. realResolves++;
  138. const newRequest =
  139. /** @type {ResolveRequestWithCacheMiss} */
  140. ({
  141. _ResolverCachePluginCacheMiss: true,
  142. ...request
  143. });
  144. /** @type {ResolveContext} */
  145. const newResolveContext = {
  146. ...resolveContext,
  147. stack: new Set(),
  148. /** @type {LazySet<string>} */
  149. missingDependencies: new LazySet(),
  150. /** @type {LazySet<string>} */
  151. fileDependencies: new LazySet(),
  152. /** @type {LazySet<string>} */
  153. contextDependencies: new LazySet()
  154. };
  155. /** @type {ResolveRequest[] | undefined} */
  156. let yieldResult;
  157. let withYield = false;
  158. if (typeof newResolveContext.yield === "function") {
  159. yieldResult = [];
  160. withYield = true;
  161. newResolveContext.yield = obj =>
  162. /** @type {ResolveRequest[]} */
  163. (yieldResult).push(obj);
  164. }
  165. /**
  166. * @param {"fileDependencies" | "contextDependencies" | "missingDependencies"} key key
  167. */
  168. const propagate = key => {
  169. if (resolveContext[key]) {
  170. addAllToSet(
  171. /** @type {Set<string>} */ (resolveContext[key]),
  172. /** @type {Set<string>} */ (newResolveContext[key])
  173. );
  174. }
  175. };
  176. const resolveTime = Date.now();
  177. resolver.doResolve(
  178. resolver.hooks.resolve,
  179. newRequest,
  180. "Cache miss",
  181. newResolveContext,
  182. (err, result) => {
  183. propagate("fileDependencies");
  184. propagate("contextDependencies");
  185. propagate("missingDependencies");
  186. if (err) return callback(err);
  187. const fileDependencies = newResolveContext.fileDependencies;
  188. const contextDependencies = newResolveContext.contextDependencies;
  189. const missingDependencies = newResolveContext.missingDependencies;
  190. fileSystemInfo.createSnapshot(
  191. resolveTime,
  192. /** @type {Set<string>} */
  193. (fileDependencies),
  194. /** @type {Set<string>} */
  195. (contextDependencies),
  196. /** @type {Set<string>} */
  197. (missingDependencies),
  198. snapshotOptions,
  199. (err, snapshot) => {
  200. if (err) return callback(err);
  201. const resolveResult = withYield ? yieldResult : result;
  202. // since we intercept resolve hook
  203. // we still can get result in callback
  204. if (withYield && result)
  205. /** @type {ResolveRequest[]} */ (yieldResult).push(result);
  206. if (!snapshot) {
  207. if (resolveResult)
  208. return callback(
  209. null,
  210. /** @type {ResolveRequest} */
  211. (resolveResult)
  212. );
  213. return callback();
  214. }
  215. itemCache.store(
  216. new CacheEntry(
  217. /** @type {ResolveRequest} */
  218. (resolveResult),
  219. snapshot
  220. ),
  221. storeErr => {
  222. if (storeErr) return callback(storeErr);
  223. if (resolveResult)
  224. return callback(
  225. null,
  226. /** @type {ResolveRequest} */
  227. (resolveResult)
  228. );
  229. callback();
  230. }
  231. );
  232. }
  233. );
  234. }
  235. );
  236. };
  237. compiler.resolverFactory.hooks.resolver.intercept({
  238. factory(type, _hook) {
  239. /** @typedef {(err?: Error, resolveRequest?: ResolveRequest) => void} ActiveRequest */
  240. /** @type {Map<string, ActiveRequest[]>} */
  241. const activeRequests = new Map();
  242. /** @type {Map<string, [ActiveRequest, NonNullable<ResolveContext["yield"]>][]>} */
  243. const activeRequestsWithYield = new Map();
  244. const hook =
  245. /** @type {SyncHook<[Resolver, ResolveOptions, ResolveOptionsWithDependencyType]>} */
  246. (_hook);
  247. hook.tap("ResolverCachePlugin", (resolver, options, userOptions) => {
  248. if (/** @type {TODO} */ (options).cache !== true) return;
  249. const optionsIdent = objectToString(userOptions, false);
  250. const cacheWithContext =
  251. options.cacheWithContext !== undefined
  252. ? options.cacheWithContext
  253. : false;
  254. resolver.hooks.resolve.tapAsync(
  255. {
  256. name: "ResolverCachePlugin",
  257. stage: -100
  258. },
  259. (request, resolveContext, callback) => {
  260. if (
  261. /** @type {ResolveRequestWithCacheMiss} */
  262. (request)._ResolverCachePluginCacheMiss ||
  263. !fileSystemInfo
  264. ) {
  265. return callback();
  266. }
  267. const withYield = typeof resolveContext.yield === "function";
  268. const identifier = `${type}${
  269. withYield ? "|yield" : "|default"
  270. }${optionsIdent}${objectToString(request, !cacheWithContext)}`;
  271. if (withYield) {
  272. const activeRequest = activeRequestsWithYield.get(identifier);
  273. if (activeRequest) {
  274. activeRequest[0].push(callback);
  275. activeRequest[1].push(
  276. /** @type {NonNullable<ResolveContext["yield"]>} */
  277. (resolveContext.yield)
  278. );
  279. return;
  280. }
  281. } else {
  282. const activeRequest = activeRequests.get(identifier);
  283. if (activeRequest) {
  284. activeRequest.push(callback);
  285. return;
  286. }
  287. }
  288. const itemCache = cache.getItemCache(identifier, null);
  289. /** @type {Callback[] | false | undefined} */
  290. let callbacks;
  291. /** @type {NonNullable<ResolveContext["yield"]>[] | undefined} */
  292. let yields;
  293. /**
  294. * @type {(err?: Error | null, result?: ResolveRequest | ResolveRequest[] | null) => void}
  295. */
  296. const done = withYield
  297. ? (err, result) => {
  298. if (callbacks === undefined) {
  299. if (err) {
  300. callback(err);
  301. } else {
  302. if (result)
  303. for (const r of /** @type {ResolveRequest[]} */ (
  304. result
  305. )) {
  306. /** @type {NonNullable<ResolveContext["yield"]>} */
  307. (resolveContext.yield)(r);
  308. }
  309. callback(null, null);
  310. }
  311. yields = undefined;
  312. callbacks = false;
  313. } else {
  314. const definedCallbacks =
  315. /** @type {Callback[]} */
  316. (callbacks);
  317. if (err) {
  318. for (const cb of definedCallbacks) cb(err);
  319. } else {
  320. for (let i = 0; i < definedCallbacks.length; i++) {
  321. const cb = definedCallbacks[i];
  322. const yield_ =
  323. /** @type {NonNullable<ResolveContext["yield"]>[]} */
  324. (yields)[i];
  325. if (result)
  326. for (const r of /** @type {ResolveRequest[]} */ (
  327. result
  328. ))
  329. yield_(r);
  330. cb(null, null);
  331. }
  332. }
  333. activeRequestsWithYield.delete(identifier);
  334. yields = undefined;
  335. callbacks = false;
  336. }
  337. }
  338. : (err, result) => {
  339. if (callbacks === undefined) {
  340. callback(err, /** @type {ResolveRequest} */ (result));
  341. callbacks = false;
  342. } else {
  343. for (const callback of /** @type {Callback[]} */ (
  344. callbacks
  345. )) {
  346. callback(err, /** @type {ResolveRequest} */ (result));
  347. }
  348. activeRequests.delete(identifier);
  349. callbacks = false;
  350. }
  351. };
  352. /**
  353. * @param {(Error | null)=} err error if any
  354. * @param {(CacheEntry | null)=} cacheEntry cache entry
  355. * @returns {void}
  356. */
  357. const processCacheResult = (err, cacheEntry) => {
  358. if (err) return done(err);
  359. if (cacheEntry) {
  360. const { snapshot, result } = cacheEntry;
  361. fileSystemInfo.checkSnapshotValid(snapshot, (err, valid) => {
  362. if (err || !valid) {
  363. cacheInvalidResolves++;
  364. return doRealResolve(
  365. itemCache,
  366. resolver,
  367. resolveContext,
  368. request,
  369. done
  370. );
  371. }
  372. cachedResolves++;
  373. if (resolveContext.missingDependencies) {
  374. addAllToSet(
  375. /** @type {Set<string>} */
  376. (resolveContext.missingDependencies),
  377. snapshot.getMissingIterable()
  378. );
  379. }
  380. if (resolveContext.fileDependencies) {
  381. addAllToSet(
  382. /** @type {Set<string>} */
  383. (resolveContext.fileDependencies),
  384. snapshot.getFileIterable()
  385. );
  386. }
  387. if (resolveContext.contextDependencies) {
  388. addAllToSet(
  389. /** @type {Set<string>} */
  390. (resolveContext.contextDependencies),
  391. snapshot.getContextIterable()
  392. );
  393. }
  394. done(null, result);
  395. });
  396. } else {
  397. doRealResolve(
  398. itemCache,
  399. resolver,
  400. resolveContext,
  401. request,
  402. done
  403. );
  404. }
  405. };
  406. itemCache.get(processCacheResult);
  407. if (withYield && callbacks === undefined) {
  408. callbacks = [callback];
  409. yields = [
  410. /** @type {NonNullable<ResolveContext["yield"]>} */
  411. (resolveContext.yield)
  412. ];
  413. activeRequestsWithYield.set(
  414. identifier,
  415. /** @type {[any, any]} */ ([callbacks, yields])
  416. );
  417. } else if (callbacks === undefined) {
  418. callbacks = [callback];
  419. activeRequests.set(identifier, callbacks);
  420. }
  421. }
  422. );
  423. });
  424. return hook;
  425. }
  426. });
  427. }
  428. }
  429. module.exports = ResolverCachePlugin;