Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
QuiteAFancyEmerald
GitHub Repository: QuiteAFancyEmerald/Holy-Unblocker
Path: blob/master/lib/rammerhead/src/util/addJSDiskCache.js
6530 views
1
const LRUCache = require('lru-cache');
2
const LRUFiles = require('keyv-lru-files');
3
const crypto = require('crypto');
4
const fs = require('fs');
5
6
let cacheGet = async (_key) => {
7
throw new TypeError('cannot cache get: must initialize cache settings first');
8
};
9
let cacheSet = async (_key, _value) => {
10
throw new TypeError('cannot cache set: must initialize cache settings first');
11
};
12
13
module.exports = async function (diskJsCachePath, jsCacheSize) {
14
const md5 = (data) => crypto.createHash('md5').update(data).digest('hex');
15
16
if (!diskJsCachePath) {
17
const jsLRUMemCache = new LRUCache({
18
max: jsCacheSize,
19
length: (n) => n.length
20
});
21
cacheGet = (key) => jsLRUMemCache.get(md5(key));
22
cacheSet = (key, value) => jsLRUMemCache.set(md5(key), value);
23
} else {
24
if (!fs.existsSync(diskJsCachePath)) {
25
throw new TypeError('disk cache folder does not exist: ' + diskJsCachePath);
26
}
27
if (!fs.lstatSync(diskJsCachePath).isDirectory()) {
28
throw new TypeError('disk cache folder must be a directory: ' + diskJsCachePath);
29
}
30
const jsLRUFileCache = new LRUFiles({
31
dir: diskJsCachePath,
32
size: jsCacheSize
33
});
34
await jsLRUFileCache.open_sqlite();
35
cacheGet = async (key) => (await jsLRUFileCache.get(md5(key)))?.toString('utf8');
36
cacheSet = async (key, value) => await jsLRUFileCache.set(md5(key), value);
37
}
38
};
39
40
// patch ScriptResourceProcessor
41
// https://github.com/DevExpress/testcafe-hammerhead/blob/7f80940225bc1c615517455dc7d30452b0365243/src/processing/resources/script.ts#L21
42
43
const scriptProcessor = require('testcafe-hammerhead/lib/processing/resources/script');
44
const { processScript } = require('testcafe-hammerhead/lib/processing/script');
45
const { updateScriptImportUrls } = require('testcafe-hammerhead/lib/utils/url');
46
const BUILTIN_HEADERS = require('testcafe-hammerhead/lib/request-pipeline/builtin-header-names');
47
48
scriptProcessor.__proto__.processResource = async function processResource(script, ctx, _charset, urlReplacer) {
49
if (!script) return script;
50
51
let processedScript = await cacheGet(script);
52
53
if (!processedScript) {
54
processedScript = processScript(
55
script,
56
true,
57
false,
58
urlReplacer,
59
ctx.destRes.headers[BUILTIN_HEADERS.serviceWorkerAllowed]
60
);
61
await cacheSet(script, processedScript);
62
} else processedScript = updateScriptImportUrls(processedScript, ctx.serverInfo, ctx.session.id, ctx.windowId);
63
64
return processedScript;
65
};
66
67