Skip to content

Commit cc6a4c9

Browse files
committed
fix: ensure resolver reinitializes when options change
1 parent d9f51f9 commit cc6a4c9

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

src/index.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,21 @@ import { isBuiltin } from 'node:module'
33
import { dirname } from 'node:path'
44
import { ResolverFactory } from 'oxc-resolver'
55
import { normalizeOptions } from './normalizeOptions'
6+
import { hashObject } from './utils'
67

8+
let cacheOptionsHash: string | undefined
79
let resolver: ResolverFactory | undefined
8-
export function resolve(source: string, file: string, options: NapiResolveOptions | null = {}): { found: boolean, path: string | null | undefined } {
10+
export function resolve(source: string, file: string, options?: NapiResolveOptions | null): { found: boolean, path: string | null | undefined } {
911
if (isBuiltin(source))
1012
return { found: true, path: null }
1113

12-
if (!resolver) {
14+
options ??= {}
15+
const optionsHash = hashObject(options)
16+
17+
if (!resolver || cacheOptionsHash !== optionsHash) {
1318
options = normalizeOptions(options)
1419
resolver = new ResolverFactory(options)
20+
cacheOptionsHash = optionsHash
1521
}
1622

1723
// https://github.com/oxc-project/oxc-resolver/blob/main/npm/README.md#api

src/utils.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import type { NapiResolveOptions } from 'oxc-resolver'
2+
import { createHash } from 'node:crypto'
3+
4+
export const hashCache = new WeakMap<NapiResolveOptions, string>()
5+
6+
export function generateHash(obj: any): string {
7+
function normalize(obj: any): string {
8+
if (obj === null || obj === 'undefined') {
9+
return 'null'
10+
} else if (typeof obj !== 'object') {
11+
return obj.toString()
12+
} else if (Array.isArray(obj)) {
13+
return `[${obj.map(normalize).sort().join(',')}]`
14+
}
15+
const sortedKeys = Object.keys(obj).sort()
16+
return `{${sortedKeys.map((key) => `${key}:${normalize(obj[key])}`).join(',')}}`
17+
}
18+
19+
const normalizedString = normalize(obj)
20+
return createHash('md5').update(normalizedString).digest('hex')
21+
}
22+
23+
export function hashObject(obj: NapiResolveOptions): string {
24+
if (hashCache.has(obj)) {
25+
return hashCache.get(obj)!
26+
}
27+
28+
const hash = generateHash(obj)
29+
hashCache.set(obj, hash)
30+
return hash
31+
}

0 commit comments

Comments
 (0)