@@ -0,0 +1,171 @@
1+/* personal-assistant-thing/src/lib/cache.ts */
2+
3+import { promises as fs } from "fs";
4+import { join } from "path";
5+import { debug } from "./debug";
6+
7+/**
8+ * Cache entry with optional expiration timestamp.
9+ */
10+interface CacheEntry<T> {
11+ value: T;
12+ expiresAt?: number; // Unix timestamp in milliseconds
13+}
14+
15+/**
16+ * Cache data structure stored on disk.
17+ */
18+interface CacheData {
19+ [key: string]: CacheEntry<any>;
20+}
21+
22+const CACHE_FILE = join(process.cwd(), "data", "cache.json");
23+
24+/**
25+ * Loads cache data from disk.
26+ * Returns empty object if file doesn't exist or can't be read.
27+ *
28+ * @returns Cache data object
29+ */
30+async function loadCache(): Promise<CacheData> {
31+ try {
32+ const data = await fs.readFile(CACHE_FILE, "utf-8");
33+ const cache = JSON.parse(data) as CacheData;
34+
35+ // Clean up expired entries
36+ const now = Date.now();
37+ const cleanedCache: CacheData = {};
38+ for (const [key, entry] of Object.entries(cache)) {
39+ if (!entry.expiresAt || entry.expiresAt > now) {
40+ cleanedCache[key] = entry;
41+ }
42+ }
43+
44+ // If we removed expired entries, save the cleaned cache
45+ if (Object.keys(cleanedCache).length !== Object.keys(cache).length) {
46+ await saveCache(cleanedCache);
47+ }
48+
49+ return cleanedCache;
50+ } catch (error: any) {
51+ // File doesn't exist or can't be read - this is fine
52+ if (error.code === "ENOENT") {
53+ debug(`[Cache] No existing cache file found, starting fresh`);
54+ return {};
55+ }
56+ debug(`[Cache] Error loading cache: ${error.message}`);
57+ return {};
58+ }
59+}
60+
61+/**
62+ * Saves cache data to disk.
63+ * Creates the data directory if it doesn't exist.
64+ *
65+ * @param cache - The cache data to save
66+ */
67+async function saveCache(cache: CacheData): Promise<void> {
68+ try {
69+ const dataDir = join(process.cwd(), "data");
70+ // Ensure data directory exists
71+ try {
72+ await fs.access(dataDir);
73+ } catch {
74+ await fs.mkdir(dataDir, { recursive: true });
75+ }
76+
77+ await fs.writeFile(CACHE_FILE, JSON.stringify(cache, null, 2), "utf-8");
78+ debug(`[Cache] Cache saved to ${CACHE_FILE}`);
79+ } catch (error: any) {
80+ debug(`[Cache] Error saving cache: ${error.message}`);
81+ // Don't throw - cache operations should continue even if persistence fails
82+ }
83+}
84+
85+/**
86+ * Sets a value in the cache with an optional TTL (time-to-live).
87+ *
88+ * @param key - The cache key
89+ * @param value - The value to cache (must be JSON-serializable)
90+ * @param ttlMs - Optional time-to-live in milliseconds. If provided, the entry will expire after this duration.
91+ * @returns Promise that resolves when the value is cached
92+ */
93+export async function setCache<T>(key: string, value: T, ttlMs?: number): Promise<void> {
94+ const cache = await loadCache();
95+ const entry: CacheEntry<T> = {
96+ value,
97+ };
98+
99+ if (ttlMs && ttlMs > 0) {
100+ entry.expiresAt = Date.now() + ttlMs;
101+ }
102+
103+ cache[key] = entry;
104+ await saveCache(cache);
105+ debug(`[Cache] Set key: ${key}${ttlMs ? ` (TTL: ${ttlMs}ms)` : ""}`);
106+}
107+
108+/**
109+ * Gets a value from the cache.
110+ *
111+ * @param key - The cache key
112+ * @returns The cached value, or null if not found or expired
113+ */
114+export async function getCache<T>(key: string): Promise<T | null> {
115+ const cache = await loadCache();
116+ const entry = cache[key];
117+
118+ if (!entry) {
119+ debug(`[Cache] Cache miss for key: ${key}`);
120+ return null;
121+ }
122+
123+ // Check if expired
124+ if (entry.expiresAt && entry.expiresAt <= Date.now()) {
125+ // Remove expired entry
126+ delete cache[key];
127+ await saveCache(cache);
128+ debug(`[Cache] Cache expired for key: ${key}`);
129+ return null;
130+ }
131+
132+ debug(`[Cache] Cache hit for key: ${key}`);
133+ return entry.value as T;
134+}
135+
136+/**
137+ * Removes a key from the cache.
138+ *
139+ * @param key - The cache key to remove
140+ * @returns Promise that resolves when the key is removed
141+ */
142+export async function deleteCache(key: string): Promise<void> {
143+ const cache = await loadCache();
144+ if (key in cache) {
145+ delete cache[key];
146+ await saveCache(cache);
147+ debug(`[Cache] Deleted key: ${key}`);
148+ }
149+}
150+
151+/**
152+ * Clears all entries from the cache.
153+ *
154+ * @returns Promise that resolves when the cache is cleared
155+ */
156+export async function clearCache(): Promise<void> {
157+ await saveCache({});
158+ debug(`[Cache] Cache cleared`);
159+}
160+
161+/**
162+ * Checks if a key exists in the cache and is not expired.
163+ *
164+ * @param key - The cache key to check
165+ * @returns true if the key exists and is not expired, false otherwise
166+ */
167+export async function hasCache(key: string): Promise<boolean> {
168+ const value = await getCache(key);
169+ return value !== null;
170+}
171+