Path: blob/master/lib/rammerhead/src/util/addJSDiskCache.js
6530 views
const LRUCache = require('lru-cache');1const LRUFiles = require('keyv-lru-files');2const crypto = require('crypto');3const fs = require('fs');45let cacheGet = async (_key) => {6throw new TypeError('cannot cache get: must initialize cache settings first');7};8let cacheSet = async (_key, _value) => {9throw new TypeError('cannot cache set: must initialize cache settings first');10};1112module.exports = async function (diskJsCachePath, jsCacheSize) {13const md5 = (data) => crypto.createHash('md5').update(data).digest('hex');1415if (!diskJsCachePath) {16const jsLRUMemCache = new LRUCache({17max: jsCacheSize,18length: (n) => n.length19});20cacheGet = (key) => jsLRUMemCache.get(md5(key));21cacheSet = (key, value) => jsLRUMemCache.set(md5(key), value);22} else {23if (!fs.existsSync(diskJsCachePath)) {24throw new TypeError('disk cache folder does not exist: ' + diskJsCachePath);25}26if (!fs.lstatSync(diskJsCachePath).isDirectory()) {27throw new TypeError('disk cache folder must be a directory: ' + diskJsCachePath);28}29const jsLRUFileCache = new LRUFiles({30dir: diskJsCachePath,31size: jsCacheSize32});33await jsLRUFileCache.open_sqlite();34cacheGet = async (key) => (await jsLRUFileCache.get(md5(key)))?.toString('utf8');35cacheSet = async (key, value) => await jsLRUFileCache.set(md5(key), value);36}37};3839// patch ScriptResourceProcessor40// https://github.com/DevExpress/testcafe-hammerhead/blob/7f80940225bc1c615517455dc7d30452b0365243/src/processing/resources/script.ts#L214142const scriptProcessor = require('testcafe-hammerhead/lib/processing/resources/script');43const { processScript } = require('testcafe-hammerhead/lib/processing/script');44const { updateScriptImportUrls } = require('testcafe-hammerhead/lib/utils/url');45const BUILTIN_HEADERS = require('testcafe-hammerhead/lib/request-pipeline/builtin-header-names');4647scriptProcessor.__proto__.processResource = async function processResource(script, ctx, _charset, urlReplacer) {48if (!script) return script;4950let processedScript = await cacheGet(script);5152if (!processedScript) {53processedScript = processScript(54script,55true,56false,57urlReplacer,58ctx.destRes.headers[BUILTIN_HEADERS.serviceWorkerAllowed]59);60await cacheSet(script, processedScript);61} else processedScript = updateScriptImportUrls(processedScript, ctx.serverInfo, ctx.session.id, ctx.windowId);6263return processedScript;64};656667