ModuleCache.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. exports.__esModule = true;
  3. const log = require('debug')('eslint-module-utils:ModuleCache');
  4. /** @type {import('./ModuleCache').ModuleCache} */
  5. class ModuleCache {
  6. /** @param {typeof import('./ModuleCache').ModuleCache.prototype.map} map */
  7. constructor(map) {
  8. this.map = map || /** @type {{typeof import('./ModuleCache').ModuleCache.prototype.map} */ new Map();
  9. }
  10. /** @type {typeof import('./ModuleCache').ModuleCache.prototype.set} */
  11. set(cacheKey, result) {
  12. this.map.set(cacheKey, { result, lastSeen: process.hrtime() });
  13. log('setting entry for', cacheKey);
  14. return result;
  15. }
  16. /** @type {typeof import('./ModuleCache').ModuleCache.prototype.get} */
  17. get(cacheKey, settings) {
  18. if (this.map.has(cacheKey)) {
  19. const f = this.map.get(cacheKey);
  20. // check freshness
  21. // @ts-expect-error TS can't narrow properly from `has` and `get`
  22. if (process.hrtime(f.lastSeen)[0] < settings.lifetime) { return f.result; }
  23. } else {
  24. log('cache miss for', cacheKey);
  25. }
  26. // cache miss
  27. return undefined;
  28. }
  29. /** @type {typeof import('./ModuleCache').ModuleCache.getSettings} */
  30. static getSettings(settings) {
  31. /** @type {ReturnType<typeof ModuleCache.getSettings>} */
  32. const cacheSettings = Object.assign({
  33. lifetime: 30, // seconds
  34. }, settings['import/cache']);
  35. // parse infinity
  36. // @ts-expect-error the lack of type overlap is because we're abusing `cacheSettings` as a temporary object
  37. if (cacheSettings.lifetime === '∞' || cacheSettings.lifetime === 'Infinity') {
  38. cacheSettings.lifetime = Infinity;
  39. }
  40. return cacheSettings;
  41. }
  42. }
  43. exports.default = ModuleCache;