file-watcher-api.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /** @typedef {import("webpack/lib/Compilation.js")} WebpackCompilation */
  2. /** @typedef {{timestamp: number, fileDependencies: string[]}} Snapshot */
  3. 'use strict';
  4. /**
  5. *
  6. * @param {{fileDependencies: string[], contextDependencies: string[], missingDependencies: string[]}} fileDependencies
  7. * @param {WebpackCompilation} compilation
  8. * @param {number} startTime
  9. */
  10. function createSnapshot (fileDependencies, compilation, startTime) {
  11. const flatDependencies = [];
  12. Object.keys(fileDependencies).forEach((depencyTypes) => {
  13. fileDependencies[depencyTypes].forEach(fileDependency => {
  14. flatDependencies.push(fileDependency);
  15. });
  16. });
  17. return {
  18. fileDependencies: flatDependencies,
  19. timestamp: startTime
  20. };
  21. }
  22. /**
  23. * Returns true if the files inside this snapshot
  24. * have not been changed
  25. *
  26. * @param {Snapshot} snapshot
  27. * @param {WebpackCompilation} compilation
  28. * @returns {Promise<boolean>}
  29. */
  30. function isSnapShotValid (snapshot, compilation) {
  31. // Check if any dependent file was changed after the last compilation
  32. const fileTimestamps = compilation.fileTimestamps;
  33. const isCacheOutOfDate = snapshot.fileDependencies.some((fileDependency) => {
  34. const timestamp = fileTimestamps.get(fileDependency);
  35. // If the timestamp is not known the file is new
  36. // If the timestamp is larger then the file has changed
  37. // Otherwise the file is still the same
  38. return !timestamp || timestamp > snapshot.timestamp;
  39. });
  40. return Promise.resolve(!isCacheOutOfDate);
  41. }
  42. /**
  43. * Ensure that the files keep watched for changes
  44. * and will trigger a recompile
  45. *
  46. * @param {WebpackCompilation} mainCompilation
  47. * @param {{fileDependencies: string[], contextDependencies: string[], missingDependencies: string[]}} fileDependencies
  48. */
  49. function watchFiles (mainCompilation, fileDependencies) {
  50. Object.keys(fileDependencies).forEach((depencyTypes) => {
  51. fileDependencies[depencyTypes].forEach(fileDependency => {
  52. mainCompilation.compilationDependencies.add(fileDependency);
  53. });
  54. });
  55. }
  56. module.exports = {
  57. createSnapshot,
  58. isSnapShotValid,
  59. watchFiles
  60. };