@trieb.work/nextjs-turbo-redis-cache 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,344 @@
1
+ import { commandOptions, createClient } from 'redis';
2
+ import { SyncedMap } from './SyncedMap';
3
+ import { DeduplicatedRequestHandler } from './DeduplicatedRequestHandler';
4
+ import {
5
+ CacheHandler,
6
+ CacheHandlerValue,
7
+ IncrementalCache,
8
+ } from 'next/dist/server/lib/incremental-cache';
9
+
10
+ export type CommandOptions = ReturnType<typeof commandOptions>;
11
+ type GetParams = Parameters<IncrementalCache['get']>;
12
+ type SetParams = Parameters<IncrementalCache['set']>;
13
+ type RevalidateParams = Parameters<IncrementalCache['revalidateTag']>;
14
+ export type Client = ReturnType<typeof createClient>;
15
+
16
+ export type CreateRedisStringsHandlerOptions = {
17
+ database?: number;
18
+ keyPrefix?: string;
19
+ timeoutMs?: number;
20
+ revalidateTagQuerySize?: number;
21
+ sharedTagsKey?: string;
22
+ avgResyncIntervalMs?: number;
23
+ redisGetDeduplication?: boolean;
24
+ inMemoryCachingTime?: number;
25
+ defaultStaleAge?: number;
26
+ estimateExpireAge?: (staleAge: number) => number;
27
+ maxMemoryCacheSize?: number;
28
+ };
29
+
30
+ const NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_';
31
+ const REVALIDATED_TAGS_KEY = '__revalidated_tags__';
32
+
33
+ function isImplicitTag(tag: string): boolean {
34
+ return tag.startsWith(NEXT_CACHE_IMPLICIT_TAG_ID);
35
+ }
36
+
37
+ export function getTimeoutRedisCommandOptions(
38
+ timeoutMs: number,
39
+ ): CommandOptions {
40
+ return commandOptions({ signal: AbortSignal.timeout(timeoutMs) });
41
+ }
42
+
43
+ export default class RedisStringsHandler implements CacheHandler {
44
+ private maxMemoryCacheSize: undefined | number;
45
+ private client: Client;
46
+ private sharedTagsMap: SyncedMap<string[]>;
47
+ private revalidatedTagsMap: SyncedMap<number>;
48
+ private inMemoryDeduplicationCache: SyncedMap<
49
+ Promise<ReturnType<Client['get']>>
50
+ >;
51
+ private redisGet: Client['get'];
52
+ private redisDeduplicationHandler: DeduplicatedRequestHandler<
53
+ Client['get'],
54
+ string | Buffer | null
55
+ >;
56
+ private deduplicatedRedisGet: (key: string) => Client['get'];
57
+ private timeoutMs: number;
58
+ private keyPrefix: string;
59
+ private redisGetDeduplication: boolean;
60
+ private inMemoryCachingTime: number;
61
+ private defaultStaleAge: number;
62
+ private estimateExpireAge: (staleAge: number) => number;
63
+
64
+ constructor({
65
+ maxMemoryCacheSize,
66
+ database = process.env.VERCEL_ENV === 'production' ? 0 : 1,
67
+ keyPrefix = process.env.VERCEL_URL || 'UNDEFINED_URL_',
68
+ sharedTagsKey = '__sharedTags__',
69
+ timeoutMs = 5000,
70
+ revalidateTagQuerySize = 250,
71
+ avgResyncIntervalMs = 60 * 60 * 1000,
72
+ redisGetDeduplication = true,
73
+ inMemoryCachingTime = 10_000,
74
+ defaultStaleAge = 60 * 60 * 24 * 14,
75
+ estimateExpireAge = (staleAge) =>
76
+ process.env.VERCEL_ENV === 'preview' ? staleAge * 1.2 : staleAge * 2,
77
+ }: CreateRedisStringsHandlerOptions) {
78
+ this.maxMemoryCacheSize = maxMemoryCacheSize;
79
+ this.keyPrefix = keyPrefix;
80
+ this.timeoutMs = timeoutMs;
81
+ this.redisGetDeduplication = redisGetDeduplication;
82
+ this.inMemoryCachingTime = inMemoryCachingTime;
83
+ this.defaultStaleAge = defaultStaleAge;
84
+ this.estimateExpireAge = estimateExpireAge;
85
+
86
+ try {
87
+ this.client = createClient({
88
+ ...(database !== 0 ? { database } : {}),
89
+ url: process.env.REDISHOST
90
+ ? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`
91
+ : 'redis://localhost:6379',
92
+ });
93
+
94
+ this.client.on('error', (error) => {
95
+ console.error('Redis client error', error);
96
+ });
97
+
98
+ this.client
99
+ .connect()
100
+ .then(() => {
101
+ console.info('Redis client connected.');
102
+ })
103
+ .catch((error) => {
104
+ console.error('Failed to connect Redis client:', error);
105
+ this.client.disconnect();
106
+ });
107
+ } catch (error: unknown) {
108
+ console.error('Failed to initialize Redis client');
109
+ throw error;
110
+ }
111
+
112
+ const filterKeys = (key: string): boolean =>
113
+ key !== REVALIDATED_TAGS_KEY && key !== sharedTagsKey;
114
+
115
+ this.sharedTagsMap = new SyncedMap<string[]>({
116
+ client: this.client,
117
+ keyPrefix,
118
+ redisKey: sharedTagsKey,
119
+ database,
120
+ timeoutMs,
121
+ querySize: revalidateTagQuerySize,
122
+ filterKeys,
123
+ resyncIntervalMs:
124
+ avgResyncIntervalMs -
125
+ avgResyncIntervalMs / 10 +
126
+ Math.random() * (avgResyncIntervalMs / 10),
127
+ });
128
+
129
+ this.revalidatedTagsMap = new SyncedMap<number>({
130
+ client: this.client,
131
+ keyPrefix,
132
+ redisKey: REVALIDATED_TAGS_KEY,
133
+ database,
134
+ timeoutMs,
135
+ querySize: revalidateTagQuerySize,
136
+ filterKeys,
137
+ resyncIntervalMs:
138
+ avgResyncIntervalMs +
139
+ avgResyncIntervalMs / 10 +
140
+ Math.random() * (avgResyncIntervalMs / 10),
141
+ });
142
+
143
+ this.inMemoryDeduplicationCache = new SyncedMap({
144
+ client: this.client,
145
+ keyPrefix,
146
+ redisKey: 'inMemoryDeduplicationCache',
147
+ database,
148
+ timeoutMs,
149
+ querySize: revalidateTagQuerySize,
150
+ filterKeys,
151
+ customizedSync: {
152
+ withoutRedisHashmap: true,
153
+ withoutSetSync: true,
154
+ },
155
+ });
156
+
157
+ const redisGet: Client['get'] = this.client.get.bind(this.client);
158
+ this.redisDeduplicationHandler = new DeduplicatedRequestHandler(
159
+ redisGet,
160
+ inMemoryCachingTime,
161
+ this.inMemoryDeduplicationCache,
162
+ );
163
+ this.redisGet = redisGet;
164
+ this.deduplicatedRedisGet =
165
+ this.redisDeduplicationHandler.deduplicatedFunction;
166
+ }
167
+ resetRequestCache(...args: never[]): void {
168
+ console.warn('WARNING resetRequestCache() was called', args);
169
+ }
170
+
171
+ private async assertClientIsReady(): Promise<void> {
172
+ await Promise.all([
173
+ this.sharedTagsMap.waitUntilReady(),
174
+ this.revalidatedTagsMap.waitUntilReady(),
175
+ ]);
176
+ if (!this.client.isReady) {
177
+ throw new Error('Redis client is not ready yet or connection is lost.');
178
+ }
179
+ }
180
+
181
+ public async get(key: GetParams[0], ctx: GetParams[1]) {
182
+ await this.assertClientIsReady();
183
+
184
+ const clientGet = this.redisGetDeduplication
185
+ ? this.deduplicatedRedisGet(key)
186
+ : this.redisGet;
187
+ const result = await clientGet(
188
+ getTimeoutRedisCommandOptions(this.timeoutMs),
189
+ this.keyPrefix + key,
190
+ );
191
+
192
+ if (!result) {
193
+ return null;
194
+ }
195
+
196
+ const cacheValue = JSON.parse(result) as
197
+ | (CacheHandlerValue & { lastModified: number })
198
+ | null;
199
+
200
+ if (!cacheValue) {
201
+ return null;
202
+ }
203
+
204
+ if (cacheValue.value?.kind === 'FETCH') {
205
+ cacheValue.value.data.body = Buffer.from(
206
+ cacheValue.value.data.body,
207
+ ).toString('base64');
208
+ }
209
+
210
+ const combinedTags = new Set([
211
+ ...(ctx?.softTags || []),
212
+ ...(ctx?.tags || []),
213
+ ]);
214
+
215
+ if (combinedTags.size === 0) {
216
+ return cacheValue;
217
+ }
218
+
219
+ for (const tag of combinedTags) {
220
+ // TODO: check how this revalidatedTagsMap is used or if it can be deleted
221
+ const revalidationTime = this.revalidatedTagsMap.get(tag);
222
+ if (revalidationTime && revalidationTime > cacheValue.lastModified) {
223
+ const redisKey = this.keyPrefix + key;
224
+ // Do not await here as this can happen in the background while we can already serve the cacheValue
225
+ this.client
226
+ .unlink(getTimeoutRedisCommandOptions(this.timeoutMs), redisKey)
227
+ .catch((err) => {
228
+ console.error(
229
+ 'Error occurred while unlinking stale data. Retrying now. Error was:',
230
+ err,
231
+ );
232
+ this.client.unlink(
233
+ getTimeoutRedisCommandOptions(this.timeoutMs),
234
+ redisKey,
235
+ );
236
+ })
237
+ .finally(async () => {
238
+ await this.sharedTagsMap.delete(key);
239
+ await this.revalidatedTagsMap.delete(tag);
240
+ });
241
+ return null;
242
+ }
243
+ }
244
+
245
+ return cacheValue;
246
+ }
247
+ public async set(
248
+ key: SetParams[0],
249
+ data: SetParams[1] & { lastModified: number },
250
+ ctx: SetParams[2],
251
+ ) {
252
+ if (data.kind === 'FETCH') {
253
+ console.time('encoding' + key);
254
+ data.data.body = Buffer.from(data.data.body, 'base64').toString();
255
+ console.timeEnd('encoding' + key);
256
+ }
257
+ await this.assertClientIsReady();
258
+
259
+ data.lastModified = Date.now();
260
+
261
+ const value = JSON.stringify(data);
262
+
263
+ // pre seed data into deduplicated get client. This will reduce redis load by not requesting
264
+ // the same value from redis which was just set.
265
+ if (this.redisGetDeduplication) {
266
+ this.redisDeduplicationHandler.seedRequestReturn(key, value);
267
+ }
268
+
269
+ const expireAt =
270
+ ctx.revalidate &&
271
+ Number.isSafeInteger(ctx.revalidate) &&
272
+ ctx.revalidate > 0
273
+ ? this.estimateExpireAge(ctx.revalidate)
274
+ : this.estimateExpireAge(this.defaultStaleAge);
275
+ const options = getTimeoutRedisCommandOptions(this.timeoutMs);
276
+ const setOperation: Promise<string | null> = this.client.set(
277
+ options,
278
+ this.keyPrefix + key,
279
+ value,
280
+ {
281
+ EX: expireAt,
282
+ },
283
+ );
284
+
285
+ let setTagsOperation: Promise<void> | undefined;
286
+ if (ctx.tags && ctx.tags.length > 0) {
287
+ const currentTags = this.sharedTagsMap.get(key);
288
+ const currentIsSameAsNew =
289
+ currentTags?.length === ctx.tags.length &&
290
+ currentTags.every((v) => ctx.tags!.includes(v)) &&
291
+ ctx.tags.every((v) => currentTags.includes(v));
292
+
293
+ if (!currentIsSameAsNew) {
294
+ setTagsOperation = this.sharedTagsMap.set(
295
+ key,
296
+ structuredClone(ctx.tags) as string[],
297
+ );
298
+ }
299
+ }
300
+
301
+ await Promise.all([setOperation, setTagsOperation]);
302
+ }
303
+ public async revalidateTag(tagOrTags: RevalidateParams[0]) {
304
+ const tags = new Set([tagOrTags || []].flat());
305
+ await this.assertClientIsReady();
306
+
307
+ // TODO: check how this revalidatedTagsMap is used or if it can be deleted
308
+ for (const tag of tags) {
309
+ if (isImplicitTag(tag)) {
310
+ const now = Date.now();
311
+ await this.revalidatedTagsMap.set(tag, now);
312
+ }
313
+ }
314
+
315
+ const keysToDelete: string[] = [];
316
+
317
+ for (const [key, sharedTags] of this.sharedTagsMap.entries()) {
318
+ if (sharedTags.some((tag) => tags.has(tag))) {
319
+ keysToDelete.push(key);
320
+ }
321
+ }
322
+
323
+ if (keysToDelete.length === 0) {
324
+ return;
325
+ }
326
+
327
+ const fullRedisKeys = keysToDelete.map((key) => this.keyPrefix + key);
328
+
329
+ const options = getTimeoutRedisCommandOptions(this.timeoutMs);
330
+
331
+ const deleteKeysOperation = this.client.unlink(options, fullRedisKeys);
332
+
333
+ // delete entries from in-memory deduplication cache
334
+ if (this.redisGetDeduplication && this.inMemoryCachingTime > 0) {
335
+ for (const key of keysToDelete) {
336
+ this.inMemoryDeduplicationCache.delete(key);
337
+ }
338
+ }
339
+
340
+ const deleteTagsOperation = this.sharedTagsMap.delete(keysToDelete);
341
+
342
+ await Promise.all([deleteKeysOperation, deleteTagsOperation]);
343
+ }
344
+ }
@@ -0,0 +1,298 @@
1
+ // SyncedMap.ts
2
+ import { Client, getTimeoutRedisCommandOptions } from './RedisStringsHandler';
3
+
4
+ type CustomizedSync = {
5
+ withoutRedisHashmap?: boolean;
6
+ withoutSetSync?: boolean;
7
+ };
8
+
9
+ type SyncedMapOptions = {
10
+ client: Client;
11
+ keyPrefix: string;
12
+ redisKey: string; // Redis Hash key
13
+ database: number;
14
+ timeoutMs: number;
15
+ querySize: number;
16
+ filterKeys: (key: string) => boolean;
17
+ resyncIntervalMs?: number;
18
+ customizedSync?: CustomizedSync;
19
+ };
20
+
21
+ export type SyncMessage<V> = {
22
+ type: 'insert' | 'delete';
23
+ key?: string;
24
+ value?: V;
25
+ keys?: string[];
26
+ };
27
+
28
+ const SYNC_CHANNEL_SUFFIX = ':sync-channel:';
29
+ export class SyncedMap<V> {
30
+ private client: Client;
31
+ private subscriberClient: Client;
32
+ private map: Map<string, V>;
33
+ private keyPrefix: string;
34
+ private syncChannel: string;
35
+ private redisKey: string;
36
+ private database: number;
37
+ private timeoutMs: number;
38
+ private querySize: number;
39
+ private filterKeys: (key: string) => boolean;
40
+ private resyncIntervalMs?: number;
41
+ private customizedSync?: CustomizedSync;
42
+
43
+ private setupLock: Promise<void>;
44
+ private setupLockResolve!: () => void;
45
+
46
+ constructor(options: SyncedMapOptions) {
47
+ this.client = options.client;
48
+ this.keyPrefix = options.keyPrefix;
49
+ this.redisKey = options.redisKey;
50
+ this.syncChannel = `${options.keyPrefix}${SYNC_CHANNEL_SUFFIX}${options.redisKey}`;
51
+ this.database = options.database;
52
+ this.timeoutMs = options.timeoutMs;
53
+ this.querySize = options.querySize;
54
+ this.filterKeys = options.filterKeys;
55
+ this.resyncIntervalMs = options.resyncIntervalMs;
56
+ this.customizedSync = options.customizedSync;
57
+
58
+ this.map = new Map<string, V>();
59
+ this.subscriberClient = this.client.duplicate();
60
+ this.setupLock = new Promise<void>((resolve) => {
61
+ this.setupLockResolve = resolve;
62
+ });
63
+
64
+ this.setup().catch((error) => {
65
+ console.error('Failed to setup SyncedMap:', error);
66
+ throw error;
67
+ });
68
+ }
69
+
70
+ private async setup() {
71
+ let setupPromises: Promise<void>[] = [];
72
+ if (!this.customizedSync?.withoutRedisHashmap) {
73
+ setupPromises.push(this.initialSync());
74
+ this.setupPeriodicResync();
75
+ }
76
+ setupPromises.push(this.setupPubSub());
77
+ await Promise.all(setupPromises);
78
+ this.setupLockResolve();
79
+ }
80
+
81
+ private async initialSync() {
82
+ let cursor = 0;
83
+ const hScanOptions = { COUNT: this.querySize };
84
+
85
+ try {
86
+ do {
87
+ const remoteItems = await this.client.hScan(
88
+ getTimeoutRedisCommandOptions(this.timeoutMs),
89
+ this.keyPrefix + this.redisKey,
90
+ cursor,
91
+ hScanOptions,
92
+ );
93
+ for (const { field, value } of remoteItems.tuples) {
94
+ if (this.filterKeys(field)) {
95
+ const parsedValue = JSON.parse(value);
96
+ this.map.set(field, parsedValue);
97
+ }
98
+ }
99
+ cursor = remoteItems.cursor;
100
+ } while (cursor !== 0);
101
+
102
+ // Clean up keys not in Redis
103
+ await this.cleanupKeysNotInRedis();
104
+ } catch (error) {
105
+ console.error('Error during initial sync:', error);
106
+ throw error;
107
+ }
108
+ }
109
+
110
+ private async cleanupKeysNotInRedis() {
111
+ let cursor = 0;
112
+ const scanOptions = { COUNT: this.querySize, MATCH: `${this.keyPrefix}*` };
113
+ let remoteKeys: string[] = [];
114
+ try {
115
+ do {
116
+ const remoteKeysPortion = await this.client.scan(
117
+ getTimeoutRedisCommandOptions(this.timeoutMs),
118
+ cursor,
119
+ scanOptions,
120
+ );
121
+ remoteKeys = remoteKeys.concat(remoteKeysPortion.keys);
122
+ cursor = remoteKeysPortion.cursor;
123
+ } while (cursor !== 0);
124
+
125
+ const remoteKeysSet = new Set(
126
+ remoteKeys.map((key) => key.substring(this.keyPrefix.length)),
127
+ );
128
+
129
+ const keysToDelete: string[] = [];
130
+ for (const key of this.map.keys()) {
131
+ const keyStr = key as unknown as string;
132
+ if (!remoteKeysSet.has(keyStr) && this.filterKeys(keyStr)) {
133
+ keysToDelete.push(keyStr);
134
+ }
135
+ }
136
+
137
+ if (keysToDelete.length > 0) {
138
+ await this.delete(keysToDelete);
139
+ }
140
+ } catch (error) {
141
+ console.error('Error during cleanup of keys not in Redis:', error);
142
+ throw error;
143
+ }
144
+ }
145
+
146
+ private setupPeriodicResync() {
147
+ if (this.resyncIntervalMs && this.resyncIntervalMs > 0) {
148
+ setInterval(() => {
149
+ this.initialSync().catch((error) => {
150
+ console.error('Error during periodic resync:', error);
151
+ });
152
+ }, this.resyncIntervalMs);
153
+ }
154
+ }
155
+
156
+ private async setupPubSub() {
157
+ const syncHandler = async (message: string) => {
158
+ const syncMessage: SyncMessage<V> = JSON.parse(message);
159
+ if (syncMessage.type === 'insert') {
160
+ if (syncMessage.key !== undefined && syncMessage.value !== undefined) {
161
+ this.map.set(syncMessage.key, syncMessage.value);
162
+ }
163
+ } else if (syncMessage.type === 'delete') {
164
+ if (syncMessage.keys) {
165
+ for (const key of syncMessage.keys) {
166
+ this.map.delete(key);
167
+ }
168
+ }
169
+ }
170
+ };
171
+
172
+ const keyEventHandler = async (_channel: string, message: string) => {
173
+ const key = message;
174
+ if (key.startsWith(this.keyPrefix)) {
175
+ const keyInMap = key.substring(this.keyPrefix.length);
176
+ if (this.filterKeys(keyInMap)) {
177
+ await this.delete(keyInMap, true);
178
+ }
179
+ }
180
+ };
181
+
182
+ try {
183
+ await this.subscriberClient.connect();
184
+
185
+ await Promise.all([
186
+ // We use a custom channel for insert/delete For the following reason:
187
+ // With custom channel we can delete multiple entries in one message. If we would listen to unlink / del we
188
+ // could get thousands of messages for one revalidateTag (For example revalidateTag("algolia") would send an enormous amount of network packages)
189
+ // Also we can send the value in the message for insert
190
+ this.subscriberClient.subscribe(this.syncChannel, syncHandler),
191
+ // Subscribe to Redis keyspace notifications for evicted and expired keys
192
+ this.subscriberClient.subscribe(
193
+ `__keyevent@${this.database}__:evicted`,
194
+ keyEventHandler,
195
+ ),
196
+ this.subscriberClient.subscribe(
197
+ `__keyevent@${this.database}__:expired`,
198
+ keyEventHandler,
199
+ ),
200
+ ]);
201
+
202
+ // Error handling for reconnection
203
+ this.subscriberClient.on('error', async (err) => {
204
+ console.error('Subscriber client error:', err);
205
+ try {
206
+ await this.subscriberClient.quit();
207
+ this.subscriberClient = this.client.duplicate();
208
+ await this.setupPubSub();
209
+ } catch (reconnectError) {
210
+ console.error(
211
+ 'Failed to reconnect subscriber client:',
212
+ reconnectError,
213
+ );
214
+ }
215
+ });
216
+ } catch (error) {
217
+ console.error('Error setting up pub/sub client:', error);
218
+ throw error;
219
+ }
220
+ }
221
+
222
+ public async waitUntilReady() {
223
+ await this.setupLock;
224
+ }
225
+
226
+ public get(key: string): V | undefined {
227
+ return this.map.get(key);
228
+ }
229
+
230
+ public async set(key: string, value: V): Promise<void> {
231
+ this.map.set(key, value);
232
+ const operations = [];
233
+
234
+ // This is needed if we only want to sync delete commands. This is especially useful for non serializable data like a promise map
235
+ if (this.customizedSync?.withoutSetSync) {
236
+ return;
237
+ }
238
+ if (!this.customizedSync?.withoutRedisHashmap) {
239
+ const options = getTimeoutRedisCommandOptions(this.timeoutMs);
240
+ operations.push(
241
+ this.client.hSet(
242
+ options,
243
+ this.keyPrefix + this.redisKey,
244
+ key as unknown as string,
245
+ JSON.stringify(value),
246
+ ),
247
+ );
248
+ }
249
+
250
+ const insertMessage: SyncMessage<V> = {
251
+ type: 'insert',
252
+ key: key as unknown as string,
253
+ value,
254
+ };
255
+ operations.push(
256
+ this.client.publish(this.syncChannel, JSON.stringify(insertMessage)),
257
+ );
258
+ await Promise.all(operations);
259
+ }
260
+
261
+ public async delete(
262
+ keys: string[] | string,
263
+ withoutSyncMessage = false,
264
+ ): Promise<void> {
265
+ const keysArray = Array.isArray(keys) ? keys : [keys];
266
+ const operations = [];
267
+
268
+ for (const key of keysArray) {
269
+ this.map.delete(key);
270
+ }
271
+
272
+ if (!this.customizedSync?.withoutRedisHashmap) {
273
+ const options = getTimeoutRedisCommandOptions(this.timeoutMs);
274
+ operations.push(
275
+ this.client.hDel(options, this.keyPrefix + this.redisKey, keysArray),
276
+ );
277
+ }
278
+
279
+ if (!withoutSyncMessage) {
280
+ const deletionMessage: SyncMessage<V> = {
281
+ type: 'delete',
282
+ keys: keysArray,
283
+ };
284
+ operations.push(
285
+ this.client.publish(this.syncChannel, JSON.stringify(deletionMessage)),
286
+ );
287
+ }
288
+ await Promise.all(operations);
289
+ }
290
+
291
+ public has(key: string): boolean {
292
+ return this.map.has(key);
293
+ }
294
+
295
+ public entries(): IterableIterator<[string, V]> {
296
+ return this.map.entries();
297
+ }
298
+ }
@@ -0,0 +1,7 @@
1
+ import { describe, it } from 'vitest';
2
+
3
+ describe('Example Test', () => {
4
+ it('should work correctly', () => {
5
+ console.log("TODO tests")
6
+ });
7
+ });
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ import CachedHandler from "./CachedHandler";
2
+ export default CachedHandler;
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "CommonJS",
5
+ "strict": true,
6
+ "esModuleInterop": true,
7
+ "skipLibCheck": true,
8
+ "declaration": true,
9
+ "outDir": "dist"
10
+ },
11
+ "include": ["src", "vitest.config.ts"],
12
+ "exclude": ["node_modules", "dist"],
13
+ "types": ["vitest"]
14
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true, // Enable global test APIs like `describe`, `it`, and `expect`
6
+ environment: 'node', // Use 'node' as the test environment
7
+ include: ['src/**/*.test.ts', 'src/**/*.test.tsx'], // Only include TypeScript test files
8
+ exclude: ['node_modules', 'dist', '.git'], // Exclude unnecessary directories
9
+ coverage: {
10
+ provider: 'v8', // Use v8 for coverage reporting
11
+ reporter: ['text', 'lcov'], // Generate text and lcov coverage reports
12
+ include: process.env.VITEST_COVERAGE_INCLUDE?.split(',') || [
13
+ 'src/**/*.ts',
14
+ ], // Use the specified files (by scripts/vitest-run-staged.cjs) or default to all files
15
+ exclude: ['node_modules', 'dist'], // Exclude specific directories from coverage
16
+ },
17
+ },
18
+ });