Debian Codegraph @

node/esbuild-sass-plugin/src/cache.ts

raw
1 import {OnLoadArgs, OnLoadResult} from 'esbuild'
2 import {promises as fsp} from 'fs'
3
4 export type LoadCacheEntry = {
5 mtimeMs: number
6 result: OnLoadResult
7 }
8
9 export type LoadCache = Map<string, LoadCacheEntry>
10
11 export type LoadCacheOptions = {
12 /**
13 * Enable the cache or pass your own Map to recycle its contents although
14 * it's advisable to use esbuild incremental or watch for repeated builds
15 *
16 * @default true
17 */
18 cache?: boolean | LoadCache
19 }
20
21 type OnLoadCallback = (args: OnLoadArgs) => (OnLoadResult | Promise<OnLoadResult>)
22
23 function createCache({cache = true}: LoadCacheOptions) {
24 if (cache === true) {
25 return new Map()
26 } else if (cache instanceof Map) {
27 return cache
28 }
29 }
30
31 export function useCache(options: LoadCacheOptions): [(loadCallback: OnLoadCallback) => OnLoadCallback, () => void] {
32 const cache = createCache(options)
33 if (cache) {
34 const mtimeMsCache = new Map<string, Promise<number>>()
35 const useDateNow = Date.now.bind(Date)
36
37 const maxMtimeMs = async (filenames: string[] = []) => {
38 for (const filename of filenames) {
39 if (!mtimeMsCache.has(filename)) {
40 mtimeMsCache.set(
41 filename,
42 fsp.stat(filename).then(stats => stats.mtimeMs).catch(useDateNow)
43 )
44 }
45 }
46 let max = 0
47 for (const filename of filenames) {
48 const mtimeMs = await mtimeMsCache.get(filename)!
49 if (mtimeMs > max) {
50 max = mtimeMs
51 }
52 }
53 return max
54 }
55
56 const cached = (loadCallback: OnLoadCallback): OnLoadCallback => async args => {
57 let path = args.path
58 try {
59 let cached = cache.get(path)
60 if (cached) {
61 let mtimeMs = await maxMtimeMs(cached.result.watchFiles)
62 if (mtimeMs > cached.mtimeMs) {
63 cached.result = await loadCallback(args)
64 cached.mtimeMs = mtimeMs
65 }
66 } else {
67 let result = await loadCallback(args)
68 cached = {
69 mtimeMs: await maxMtimeMs(result.watchFiles),
70 result
71 }
72 cache.set(path, cached)
73 }
74 if (cached.result.errors) {
75 cache.delete(path)
76 }
77 return cached.result
78 } catch (error) {
79 cache.delete(path)
80 throw error
81 }
82 }
83
84 return [cached, () => mtimeMsCache.clear()]
85 } else {
86 return [loadCallback => loadCallback, () => {}]
87 }
88 }
89