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