-
Notifications
You must be signed in to change notification settings - Fork 413
/
eval-cache.ts
88 lines (67 loc) · 1.97 KB
/
eval-cache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { createHash } from 'crypto';
import { debug } from './utils/logger';
const fileHashes = new Map<string, string>();
const evalCache = new Map<string, any>();
const fileKeys = new Map<string, string[]>();
const hash = (text: string) => createHash('sha1').update(text).digest('base64');
let lastText: string = '';
let lastHash: string = hash(lastText);
const memoizedHash: typeof hash = (text) => {
if (lastText !== text) {
lastHash = hash(text);
lastText = text;
}
return lastHash;
};
const toKey = (filename: string, exports: string[]) =>
exports.length > 0 ? `${filename}:${exports.join(',')}` : filename;
export const clear = () => {
fileHashes.clear();
evalCache.clear();
fileKeys.clear();
};
export const clearForFile = (filename: string) => {
const keys = fileKeys.get(filename) ?? [];
if (keys.length === 0) {
return;
}
debug('eval-cache:clear-for-file', filename);
for (const key of keys) {
fileHashes.delete(key);
evalCache.delete(key);
}
fileKeys.set(filename, []);
};
export const has = (
[filename, ...exports]: string[],
text: string
): boolean => {
const key = toKey(filename, exports);
const textHash = memoizedHash(text);
debug('eval-cache:has', `${key} ${textHash}`);
return fileHashes.get(key) === textHash;
};
export const get = ([filename, ...exports]: string[], text: string): any => {
const key = toKey(filename, exports);
const textHash = memoizedHash(text);
debug('eval-cache:get', `${key} ${textHash}`);
if (fileHashes.get(key) !== textHash) {
return undefined;
}
return evalCache.get(key);
};
export const set = (
[filename, ...exports]: string[],
text: string,
value: any
): void => {
const key = toKey(filename, exports);
const textHash = memoizedHash(text);
debug('eval-cache:set', `${key} ${textHash}`);
fileHashes.set(key, textHash);
evalCache.set(key, value);
if (!fileKeys.has(filename)) {
fileKeys.set(filename, []);
}
fileKeys.get(filename)!.push(key);
};