CleanPlugin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sergey Melyukov @smelukov
  4. */
  5. "use strict";
  6. const path = require("path");
  7. const asyncLib = require("neo-async");
  8. const { SyncBailHook } = require("tapable");
  9. const Compilation = require("./Compilation");
  10. const { join } = require("./util/fs");
  11. const processAsyncTree = require("./util/processAsyncTree");
  12. /** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */
  13. /** @typedef {import("./Compiler")} Compiler */
  14. /** @typedef {import("./logging/Logger").Logger} Logger */
  15. /** @typedef {import("./util/fs").IStats} IStats */
  16. /** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
  17. /** @typedef {import("./util/fs").StatsCallback} StatsCallback */
  18. /** @typedef {Map<string, number>} Assets */
  19. /**
  20. * Defines the clean plugin compilation hooks type used by this module.
  21. * @typedef {object} CleanPluginCompilationHooks
  22. * @property {SyncBailHook<[string], boolean | void>} keep when returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config
  23. */
  24. /**
  25. * Defines the keep fn callback.
  26. * @callback KeepFn
  27. * @param {string} path path
  28. * @returns {boolean | undefined} true, if the path should be kept
  29. */
  30. const _10sec = 10 * 1000;
  31. /**
  32. * merge assets map 2 into map 1
  33. * @param {Assets} as1 assets
  34. * @param {Assets} as2 assets
  35. * @returns {void}
  36. */
  37. const mergeAssets = (as1, as2) => {
  38. for (const [key, value1] of as2) {
  39. const value2 = as1.get(key);
  40. if (!value2 || value1 > value2) as1.set(key, value1);
  41. }
  42. };
  43. /** @typedef {Map<string, number>} CurrentAssets */
  44. /**
  45. * Returns set of directory paths.
  46. * @param {CurrentAssets} assets current assets
  47. * @returns {Set<string>} Set of directory paths
  48. */
  49. function getDirectories(assets) {
  50. /** @type {Set<string>} */
  51. const directories = new Set();
  52. /**
  53. * Adds the provided filename to this object.
  54. * @param {string} filename asset filename
  55. */
  56. const addDirectory = (filename) => {
  57. directories.add(path.dirname(filename));
  58. };
  59. // get directories of assets
  60. for (const [asset] of assets) {
  61. addDirectory(asset);
  62. }
  63. // and all parent directories
  64. for (const directory of directories) {
  65. addDirectory(directory);
  66. }
  67. return directories;
  68. }
  69. /** @typedef {Set<string>} Diff */
  70. /**
  71. * Returns diff to fs.
  72. * @param {OutputFileSystem} fs filesystem
  73. * @param {string} outputPath output path
  74. * @param {CurrentAssets} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator)
  75. * @param {(err?: Error | null, set?: Diff) => void} callback returns the filenames of the assets that shouldn't be there
  76. * @returns {void}
  77. */
  78. const getDiffToFs = (fs, outputPath, currentAssets, callback) => {
  79. const directories = getDirectories(currentAssets);
  80. /** @type {Diff} */
  81. const diff = new Set();
  82. asyncLib.forEachLimit(
  83. directories,
  84. 10,
  85. (directory, callback) => {
  86. /** @type {NonNullable<OutputFileSystem["readdir"]>} */
  87. (fs.readdir)(join(fs, outputPath, directory), (err, entries) => {
  88. if (err) {
  89. if (err.code === "ENOENT") return callback();
  90. if (err.code === "ENOTDIR") {
  91. diff.add(directory);
  92. return callback();
  93. }
  94. return callback(err);
  95. }
  96. for (const entry of /** @type {string[]} */ (entries)) {
  97. const file = entry;
  98. // Since path.normalize("./file") === path.normalize("file"),
  99. // return file directly when directory === "."
  100. const filename =
  101. directory && directory !== "." ? `${directory}/${file}` : file;
  102. if (!directories.has(filename) && !currentAssets.has(filename)) {
  103. diff.add(filename);
  104. }
  105. }
  106. callback();
  107. });
  108. },
  109. (err) => {
  110. if (err) return callback(err);
  111. callback(null, diff);
  112. }
  113. );
  114. };
  115. /**
  116. * Gets diff to old assets.
  117. * @param {Assets} currentAssets assets list
  118. * @param {Assets} oldAssets old assets list
  119. * @returns {Diff} diff
  120. */
  121. const getDiffToOldAssets = (currentAssets, oldAssets) => {
  122. /** @type {Diff} */
  123. const diff = new Set();
  124. const now = Date.now();
  125. for (const [asset, ts] of oldAssets) {
  126. if (ts >= now) continue;
  127. if (!currentAssets.has(asset)) diff.add(asset);
  128. }
  129. return diff;
  130. };
  131. /**
  132. * Processes the provided f.
  133. * @param {OutputFileSystem} fs filesystem
  134. * @param {string} filename path to file
  135. * @param {StatsCallback} callback callback for provided filename
  136. * @returns {void}
  137. */
  138. const doStat = (fs, filename, callback) => {
  139. if ("lstat" in fs) {
  140. /** @type {NonNullable<OutputFileSystem["lstat"]>} */
  141. (fs.lstat)(filename, callback);
  142. } else {
  143. fs.stat(filename, callback);
  144. }
  145. };
  146. /**
  147. * Processes the provided f.
  148. * @param {OutputFileSystem} fs filesystem
  149. * @param {string} outputPath output path
  150. * @param {boolean} dry only log instead of fs modification
  151. * @param {Logger} logger logger
  152. * @param {Diff} diff filenames of the assets that shouldn't be there
  153. * @param {KeepFn} isKept check if the entry is ignored
  154. * @param {(err?: Error, assets?: Assets) => void} callback callback
  155. * @returns {void}
  156. */
  157. const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
  158. /**
  159. * Processes the provided msg.
  160. * @param {string} msg message
  161. */
  162. const log = (msg) => {
  163. if (dry) {
  164. logger.info(msg);
  165. } else {
  166. logger.log(msg);
  167. }
  168. };
  169. /** @typedef {{ type: "check" | "unlink" | "rmdir", filename: string, parent: { remaining: number, job: Job } | undefined }} Job */
  170. /** @type {Job[]} */
  171. const jobs = Array.from(diff.keys(), (filename) => ({
  172. type: "check",
  173. filename,
  174. parent: undefined
  175. }));
  176. /** @type {Assets} */
  177. const keptAssets = new Map();
  178. processAsyncTree(
  179. jobs,
  180. 10,
  181. ({ type, filename, parent }, push, callback) => {
  182. const path = join(fs, outputPath, filename);
  183. /**
  184. * Describes how this handle error operation behaves.
  185. * @param {Error & { code?: string }} err error
  186. * @returns {void}
  187. */
  188. const handleError = (err) => {
  189. const isAlreadyRemoved = () =>
  190. new Promise((resolve) => {
  191. if (err.code === "ENOENT") {
  192. resolve(true);
  193. } else if (err.code === "EPERM") {
  194. // https://github.com/isaacs/rimraf/blob/main/src/fix-eperm.ts#L37
  195. // fs.existsSync(path) === false https://github.com/webpack/webpack/actions/runs/15493412975/job/43624272783?pr=19586
  196. doStat(fs, path, (err) => {
  197. if (err) {
  198. resolve(err.code === "ENOENT");
  199. } else {
  200. resolve(false);
  201. }
  202. });
  203. } else {
  204. resolve(false);
  205. }
  206. });
  207. isAlreadyRemoved().then((isRemoved) => {
  208. if (isRemoved) {
  209. log(`${filename} was removed during cleaning by something else`);
  210. handleParent();
  211. return callback();
  212. }
  213. return callback(err);
  214. });
  215. };
  216. const handleParent = () => {
  217. if (parent && --parent.remaining === 0) push(parent.job);
  218. };
  219. switch (type) {
  220. case "check":
  221. if (isKept(filename)) {
  222. keptAssets.set(filename, 0);
  223. // do not decrement parent entry as we don't want to delete the parent
  224. log(`${filename} will be kept`);
  225. return process.nextTick(callback);
  226. }
  227. doStat(fs, path, (err, stats) => {
  228. if (err) return handleError(err);
  229. if (!(/** @type {IStats} */ (stats).isDirectory())) {
  230. push({
  231. type: "unlink",
  232. filename,
  233. parent
  234. });
  235. return callback();
  236. }
  237. /** @type {NonNullable<OutputFileSystem["readdir"]>} */
  238. (fs.readdir)(path, (err, _entries) => {
  239. if (err) return handleError(err);
  240. /** @type {Job} */
  241. const deleteJob = {
  242. type: "rmdir",
  243. filename,
  244. parent
  245. };
  246. const entries = /** @type {string[]} */ (_entries);
  247. if (entries.length === 0) {
  248. push(deleteJob);
  249. } else {
  250. const parentToken = {
  251. remaining: entries.length,
  252. job: deleteJob
  253. };
  254. for (const entry of entries) {
  255. const file = /** @type {string} */ (entry);
  256. if (file.startsWith(".")) {
  257. log(
  258. `${filename} will be kept (dot-files will never be removed)`
  259. );
  260. continue;
  261. }
  262. push({
  263. type: "check",
  264. filename: `${filename}/${file}`,
  265. parent: parentToken
  266. });
  267. }
  268. }
  269. return callback();
  270. });
  271. });
  272. break;
  273. case "rmdir":
  274. log(`${filename} will be removed`);
  275. if (dry) {
  276. handleParent();
  277. return process.nextTick(callback);
  278. }
  279. if (!fs.rmdir) {
  280. logger.warn(
  281. `${filename} can't be removed because output file system doesn't support removing directories (rmdir)`
  282. );
  283. return process.nextTick(callback);
  284. }
  285. fs.rmdir(path, (err) => {
  286. if (err) return handleError(err);
  287. handleParent();
  288. callback();
  289. });
  290. break;
  291. case "unlink":
  292. log(`${filename} will be removed`);
  293. if (dry) {
  294. handleParent();
  295. return process.nextTick(callback);
  296. }
  297. if (!fs.unlink) {
  298. logger.warn(
  299. `${filename} can't be removed because output file system doesn't support removing files (rmdir)`
  300. );
  301. return process.nextTick(callback);
  302. }
  303. fs.unlink(path, (err) => {
  304. if (err) return handleError(err);
  305. handleParent();
  306. callback();
  307. });
  308. break;
  309. }
  310. },
  311. (err) => {
  312. if (err) return callback(err);
  313. callback(undefined, keptAssets);
  314. }
  315. );
  316. };
  317. /** @type {WeakMap<Compilation, CleanPluginCompilationHooks>} */
  318. const compilationHooksMap = new WeakMap();
  319. const PLUGIN_NAME = "CleanPlugin";
  320. class CleanPlugin {
  321. /**
  322. * Returns the attached hooks.
  323. * @param {Compilation} compilation the compilation
  324. * @returns {CleanPluginCompilationHooks} the attached hooks
  325. */
  326. static getCompilationHooks(compilation) {
  327. if (!(compilation instanceof Compilation)) {
  328. throw new TypeError(
  329. "The 'compilation' argument must be an instance of Compilation"
  330. );
  331. }
  332. let hooks = compilationHooksMap.get(compilation);
  333. if (hooks === undefined) {
  334. hooks = {
  335. keep: new SyncBailHook(["ignore"])
  336. };
  337. compilationHooksMap.set(compilation, hooks);
  338. }
  339. return hooks;
  340. }
  341. /** @param {CleanOptions} options options */
  342. constructor(options = {}) {
  343. /** @type {CleanOptions} */
  344. this.options = options;
  345. }
  346. /**
  347. * Applies the plugin by registering its hooks on the compiler.
  348. * @param {Compiler} compiler the compiler instance
  349. * @returns {void}
  350. */
  351. apply(compiler) {
  352. compiler.hooks.validate.tap(PLUGIN_NAME, () => {
  353. compiler.validate(
  354. () => {
  355. const { definitions } = require("../schemas/WebpackOptions.json");
  356. return {
  357. definitions,
  358. oneOf: [{ $ref: "#/definitions/CleanOptions" }]
  359. };
  360. },
  361. this.options,
  362. {
  363. name: "Clean Plugin",
  364. baseDataPath: "options"
  365. }
  366. );
  367. });
  368. const { keep } = this.options;
  369. /** @type {boolean} */
  370. const dry = this.options.dry || false;
  371. /** @type {KeepFn} */
  372. const keepFn =
  373. typeof keep === "function"
  374. ? keep
  375. : typeof keep === "string"
  376. ? (path) => path.startsWith(keep)
  377. : typeof keep === "object" && keep.test
  378. ? (path) => keep.test(path)
  379. : () => false;
  380. // We assume that no external modification happens while the compiler is active
  381. // So we can store the old assets and only diff to them to avoid fs access on
  382. // incremental builds
  383. /** @type {undefined | Assets} */
  384. let oldAssets;
  385. compiler.hooks.emit.tapAsync(
  386. {
  387. name: PLUGIN_NAME,
  388. stage: 100
  389. },
  390. (compilation, callback) => {
  391. const hooks = CleanPlugin.getCompilationHooks(compilation);
  392. const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`);
  393. const fs = /** @type {OutputFileSystem} */ (compiler.outputFileSystem);
  394. if (!fs.readdir) {
  395. return callback(
  396. new Error(
  397. `${PLUGIN_NAME}: Output filesystem doesn't support listing directories (readdir)`
  398. )
  399. );
  400. }
  401. /** @type {Assets} */
  402. const currentAssets = new Map();
  403. const now = Date.now();
  404. for (const asset of Object.keys(compilation.assets)) {
  405. if (/^[a-z]:\\|^\/|^\\\\/i.test(asset)) continue;
  406. /** @type {string} */
  407. let normalizedAsset;
  408. let newNormalizedAsset = asset.replace(/\\/g, "/");
  409. do {
  410. normalizedAsset = newNormalizedAsset;
  411. newNormalizedAsset = normalizedAsset.replace(
  412. /(^|\/)(?!\.\.)[^/]+\/\.\.\//g,
  413. "$1"
  414. );
  415. } while (newNormalizedAsset !== normalizedAsset);
  416. if (normalizedAsset.startsWith("../")) continue;
  417. const assetInfo = compilation.assetsInfo.get(asset);
  418. if (assetInfo && assetInfo.hotModuleReplacement) {
  419. currentAssets.set(normalizedAsset, now + _10sec);
  420. } else {
  421. currentAssets.set(normalizedAsset, 0);
  422. }
  423. }
  424. const outputPath = compilation.getPath(compiler.outputPath, {});
  425. /**
  426. * Checks whether this clean plugin is kept.
  427. * @param {string} path path
  428. * @returns {boolean | undefined} true, if needs to be kept
  429. */
  430. const isKept = (path) => {
  431. const result = hooks.keep.call(path);
  432. if (result !== undefined) return result;
  433. return keepFn(path);
  434. };
  435. /**
  436. * Processes the provided err.
  437. * @param {(Error | null)=} err err
  438. * @param {Diff=} diff diff
  439. */
  440. const diffCallback = (err, diff) => {
  441. if (err) {
  442. oldAssets = undefined;
  443. callback(err);
  444. return;
  445. }
  446. applyDiff(
  447. fs,
  448. outputPath,
  449. dry,
  450. logger,
  451. /** @type {Diff} */ (diff),
  452. isKept,
  453. (err, keptAssets) => {
  454. if (err) {
  455. oldAssets = undefined;
  456. } else {
  457. if (oldAssets) mergeAssets(currentAssets, oldAssets);
  458. oldAssets = currentAssets;
  459. if (keptAssets) mergeAssets(oldAssets, keptAssets);
  460. }
  461. callback(err);
  462. }
  463. );
  464. };
  465. if (oldAssets) {
  466. diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets));
  467. } else {
  468. getDiffToFs(fs, outputPath, currentAssets, diffCallback);
  469. }
  470. }
  471. );
  472. }
  473. }
  474. module.exports = CleanPlugin;
  475. module.exports._getDirectories = getDirectories;