import fs from 'fs'; import path from 'path'; import crypto from 'crypto'; export interface CompilationCacheEntry { hash: string; outputFiles: { [path: string]: string }; // path -> content hash timestamp: number; } export class CompilationCache { private cacheDir: string; private cache: { [key: string]: CompilationCacheEntry } = {}; constructor(cacheDir: string) { this.cacheDir = cacheDir; this.loadCache(); } private loadCache() { try { const cacheFile = path.join(this.cacheDir, 'compilation-cache.json'); if (fs.existsSync(cacheFile)) { this.cache = JSON.parse(fs.readFileSync(cacheFile, 'utf8')); } } catch (err) { // Start with empty cache if loading fails this.cache = {}; } } private saveCache() { try { if (!fs.existsSync(this.cacheDir)) { fs.mkdirSync(this.cacheDir, { recursive: true }); } fs.writeFileSync( path.join(this.cacheDir, 'compilation-cache.json'), JSON.stringify(this.cache, null, 2) ); } catch (err) { console.error('Failed to save compilation cache:', err); } } public getEntry(key: string, sourceHash: string): CompilationCacheEntry | undefined { const entry = this.cache[key]; if (entry && entry.hash === sourceHash) { return entry; } return undefined; } public setEntry(key: string, sourceHash: string, outputFiles: { [path: string]: string }) { this.cache[key] = { hash: sourceHash, outputFiles, timestamp: Date.now() }; this.saveCache(); } public clear() { this.cache = {}; this.saveCache(); } }