@@ -4,6 +4,7 @@ import { refineMeta } from "./utils"
4
4
import { isAbsolute , join } from "pathe"
5
5
import { existsSync , readFileSync , writeFileSync , mkdirSync } from 'fs'
6
6
import { withBase } from "ufo"
7
+ import { hash } from "crypto"
7
8
8
9
export interface Options {
9
10
rootDir : string
@@ -16,14 +17,23 @@ export function getComponentMeta(component: string, options?: Options): Componen
16
17
const opts = {
17
18
cache : false ,
18
19
rootDir,
19
- cacheDir : join ( rootDir , ".data/cache " ) ,
20
+ cacheDir : join ( rootDir , ".data/nuxt-component-meta " ) ,
20
21
...options
21
22
}
22
23
const fullPath = isAbsolute ( component ) ? component : withBase ( component , opts . rootDir )
23
- const cachePath = join ( opts . cacheDir , `${ component } .json` )
24
+ let cachePath = join ( opts . cacheDir , `${ component } .json` )
25
+ if ( opts . cache ) {
26
+ try {
27
+ const content = readFileSync ( fullPath , { encoding : 'utf8' , flag : 'r' } )
28
+ const cacheId = component . split ( '/' ) . pop ( ) ?. replace ( / \. / g, '_' ) + '-' + hash ( 'sha1' , content ) . slice ( 0 , 12 )
29
+ cachePath = join ( opts . cacheDir , `${ cacheId } .json` )
30
+ } catch ( error ) {
31
+ throw new Error ( `Error reading file ${ fullPath } : ${ error } ` )
32
+ }
24
33
25
- if ( opts . cache && existsSync ( cachePath ) ) {
26
- return JSON . parse ( readFileSync ( cachePath , { encoding : 'utf8' , flag : 'r' } ) ) as ComponentMeta
34
+ if ( existsSync ( cachePath ) ) {
35
+ return JSON . parse ( readFileSync ( cachePath , { encoding : 'utf8' , flag : 'r' } ) ) as ComponentMeta
36
+ }
27
37
}
28
38
29
39
const checker = createCheckerByJson (
@@ -40,7 +50,10 @@ export function getComponentMeta(component: string, options?: Options): Componen
40
50
const refinedMeta = refineMeta ( meta )
41
51
42
52
if ( opts . cache ) {
43
- const cache = JSON . stringify ( refinedMeta , null , 2 )
53
+ const cache = JSON . stringify ( {
54
+ cachedAt : Date . now ( ) ,
55
+ ...refinedMeta ,
56
+ } )
44
57
if ( ! existsSync ( opts . cacheDir ) ) {
45
58
mkdirSync ( opts . cacheDir , { recursive : true } )
46
59
}
0 commit comments