diff --git a/src/index.ts b/src/index.ts index 8dca083..ab09cf5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,4 @@ +import { AsyncLocalStorage } from 'node:async_hooks' import module, { type LoadHookContext } from 'node:module' import process from 'node:process' import { fileURLToPath } from 'node:url' @@ -13,7 +14,7 @@ export interface Options { const RE_NODE_MODULES = /[/\\]node_modules[/\\]/ -export const loaded: Set = new Set() +export const depsStore: AsyncLocalStorage> = new AsyncLocalStorage() let deregister: (() => void) | undefined export function init({ skipNodeModules }: Options = {}): () => void { @@ -45,7 +46,11 @@ export function init({ skipNodeModules }: Options = {}): () => void { const parentUUID = getParentUUID(context.parentURL) if (!noCache && !parentUUID) return resolved - loaded.add(fileURLToPath(resolved.url)) + const deps = depsStore.getStore() + if (deps) { + deps.add(fileURLToPath(resolved.url)) + } + resolved.url = appendUUID(resolved.url, parentUUID || crypto.randomUUID()) return resolved }, @@ -58,7 +63,6 @@ export function init({ skipNodeModules }: Options = {}): () => void { return (deregister = () => { hooks.deregister() - loaded.clear() deregister = undefined }) } diff --git a/tests/fixtures/deps-a.js b/tests/fixtures/deps-a.js new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/tests/fixtures/deps-a.js @@ -0,0 +1 @@ +export {} diff --git a/tests/fixtures/deps-b.js b/tests/fixtures/deps-b.js new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/tests/fixtures/deps-b.js @@ -0,0 +1 @@ +export {} diff --git a/tests/index.test.ts b/tests/index.test.ts index a6da94f..a52a987 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,6 +1,12 @@ import assert from 'node:assert' +import path from 'node:path' import { afterEach, test } from 'node:test' -import { clearRequireCache, init, unregister, loaded } from '../dist/index.mjs' +import { + clearRequireCache, + depsStore, + init, + unregister, +} from '../dist/index.mjs' afterEach(() => { unregister() @@ -25,7 +31,6 @@ test('import attributes', async () => { } = await import('./fixtures/mod.js', { with: { cache: 'no' }, }) - assert(loaded.size > 0) clearRequireCache() const { uuid: uuid3, @@ -123,3 +128,25 @@ test('data URL', async () => { assert.equal(foo, 42) }) + +test('deps store', async () => { + init() + + const depsA = new Set() + const depsB = new Set() + await Promise.all([ + depsStore.run( + depsA, + // @ts-ignore missing types + () => import('./fixtures/deps-a.js', { with: { cache: 'no' } }), + ), + depsStore.run( + depsB, + // @ts-ignore missing types + () => import('./fixtures/deps-b.js', { with: { cache: 'no' } }), + ), + ]) + + assert(depsA.has(path.resolve('./tests/fixtures/deps-a.js'))) + assert(depsB.has(path.resolve('./tests/fixtures/deps-b.js'))) +})