| 1 |
"use strict"; |
| 2 |
Object.defineProperty(exports, "__esModule", { value: true }); |
| 3 |
exports.useCache = useCache; |
| 4 |
const fs_1 = require("fs"); |
| 5 |
function createCache({ cache = true }) { |
| 6 |
if (cache === true) { |
| 7 |
return new Map(); |
| 8 |
} |
| 9 |
else if (cache instanceof Map) { |
| 10 |
return cache; |
| 11 |
} |
| 12 |
} |
| 13 |
function useCache(options) { |
| 14 |
const cache = createCache(options); |
| 15 |
if (cache) { |
| 16 |
const mtimeMsCache = new Map(); |
| 17 |
const useDateNow = Date.now.bind(Date); |
| 18 |
const maxMtimeMs = async (filenames = []) => { |
| 19 |
for (const filename of filenames) { |
| 20 |
if (!mtimeMsCache.has(filename)) { |
| 21 |
mtimeMsCache.set(filename, fs_1.promises.stat(filename).then(stats => stats.mtimeMs).catch(useDateNow)); |
| 22 |
} |
| 23 |
} |
| 24 |
let max = 0; |
| 25 |
for (const filename of filenames) { |
| 26 |
const mtimeMs = await mtimeMsCache.get(filename); |
| 27 |
if (mtimeMs > max) { |
| 28 |
max = mtimeMs; |
| 29 |
} |
| 30 |
} |
| 31 |
return max; |
| 32 |
}; |
| 33 |
const cached = (loadCallback) => async (args) => { |
| 34 |
let path = args.path; |
| 35 |
try { |
| 36 |
let cached = cache.get(path); |
| 37 |
if (cached) { |
| 38 |
let mtimeMs = await maxMtimeMs(cached.result.watchFiles); |
| 39 |
if (mtimeMs > cached.mtimeMs) { |
| 40 |
cached.result = await loadCallback(args); |
| 41 |
cached.mtimeMs = mtimeMs; |
| 42 |
} |
| 43 |
} |
| 44 |
else { |
| 45 |
let result = await loadCallback(args); |
| 46 |
cached = { |
| 47 |
mtimeMs: await maxMtimeMs(result.watchFiles), |
| 48 |
result |
| 49 |
}; |
| 50 |
cache.set(path, cached); |
| 51 |
} |
| 52 |
if (cached.result.errors) { |
| 53 |
cache.delete(path); |
| 54 |
} |
| 55 |
return cached.result; |
| 56 |
} |
| 57 |
catch (error) { |
| 58 |
cache.delete(path); |
| 59 |
throw error; |
| 60 |
} |
| 61 |
}; |
| 62 |
return [cached, () => mtimeMsCache.clear()]; |
| 63 |
} |
| 64 |
else { |
| 65 |
return [loadCallback => loadCallback, () => { }]; |
| 66 |
} |
| 67 |
} |
| 68 |
//# sourceMappingURL=cache.js.map |